Creating a List

Let’s say that we want to create a list in python from another iterable object or sequence, such as another list. For example, we have a list of numbers, and we want to create a new list that contains the cubes of the numbers from the first list. There are multiple ways to accomplish this task. Perhaps the most basic way is to use a for loop as follows:

In the above code, we use a for loop to loop over our num_list, and we add each number cubed to cube_list.

Well, it turns out that there’s an easier way to accomplish the same task, and that’s with using a list comprehension.


List Comprehensions

List comprehensions allow us to create lists from other sequences in a very concise way. We usually use list comprehensions to loop through another sequence, such as a list, and either add the elements that satisfy a certain condition, or add the result of an operation applied to each element in the sequence.

Writing a List Comprehension

A list comprehension is made up of brackets, which contain an expression, followed by a for loop, and zero or more for or if clauses. This list comprehension then creates a list that contains the expression evaluated in the context of the for and if clauses that follow it.

Let’s start with a basic list comprehension that contains only an expression and a for loop:

[ for in ]

For example, let’s see how we can create the above cube_list, or a list that contains the cubes of another list, using a list comprehension:

So what is going on in this line of code?

cube_list = [num**3 for num in num_list]

First, we notice that we have brackets that contain an expression, num3**, followed by a for loop, for num in num_list. Within the for loop, num is the parameter name we give for the elements that we are looping over in our num_list, just like in the original for loop above. We are basically saying, take **num (or the current element) from our num_list, cube it, and then add the result of that operation to our list, similar to cube_list.append(num3). Thus we are adding the output of the expression num3 **to the list we are making as it iterates over the for loop.

Note: A list comprehension behaves very similarly to the built-in map function in python.

Note on Expressions:

The expression in a list comprehension can include functions as well. For example, if we want to create a list that contains the corresponding lengths of a list of strings, we can do so with the following list comprehension:

list_of_strings = [‘hello’, ‘my’, ‘name’, ‘a’]

len_of_strings = [len(word) for word in list_of_strings]
print(len_of_strings) ## output is [5,2,4,1]

Notice how we used the built-in len function as part of our expression within the list comprehension.

#data-science #machine-learning #programming #python #coding

List Comprehensions in Python
1.10 GEEK