Wednesday, April 12, 2017

List Comprehensions in Python

List Comprehensions in Python

List comprehensions provide you a way of writing for loops more concisely. They can be useful when you want to create new lists from existing lists or iterables. For example, you can use list comprehensions to create a list of squares from a list of numbers. Similarly, you could also use some conditions on a list of numbers so that the new list you create is a subset of the original list. 

Keep in mind that you cannot write every for loop as a list comprehension. One more thing: the name "list comprehensions" can be a bit confusing because it seems to suggest that the comprehensions are only meant for working with lists. In reality, the word "list" in list comprehensions is used to indicate that you can loop over any iterable in Python and the end product would be a list. 

Loops and List Comprehensions

Basic list comprehensions that don't use any conditions have the following form:

Let's begin by writing a very basic for loop to list the first 15 multiples of 5. First, you need to create an empty list. Then, you have to iterate over a range of numbers and multiply them by 5. The new sequence of numbers that you get will consist of multiples of 5. 

The above for loop basically has the following structure: 

If you compare it with the list comprehension form that you read earlier, you can see that <the_element> is n, <the_iterable> is range(1,16), and <the_expression> is n*5. Putting these values in the list comprehension will give us the following result:

Similarly, you can also get a list with the cube of given numbers like this:

Conditions in List Comprehensions

You can also use an if condition to filter out certain values from the final list. In this case, the list comprehension takes the following form:

A basic example of this type of comprehension would be to get all the even numbers in a given range. A for loop to do this task will look like this:

The same thing could also be accomplished by using the following list comprehension:

A more complex example of using list comprehensions would be adding .. if .. else .. conditional expressions inside them. 

In this case, the order in which you lay out the statements inside the list comprehension will be different from usual if conditions. When you only have an if condition, the condition goes to the end of the comprehension. However, in the case of an .. if .. else .. expression, the positions of the for loop and the conditional expression are interchanged. The new order is:

Let's begin by writing the verbose .. if .. else .. conditional expression to get squares of even numbers and cubes of odd numbers in a given range.

The above conditional expression has the following structure:

Putting the corresponding values in the right places will give you the following list comprehension:

List Comprehensions for Nested Loops

You can also use nested loops within a list comprehension. There is no limit on the number of for loops that you can put inside a list comprehension. However, you have to keep in mind that the order of the loops should be the same in both the original code and the list comprehension. You can also add an optional if condition after each for loop.  A list comprehension with nested for loops will have the following structure:

The following examples should make everything clearer. There are two nested loops, and multiplying them together gives us multiplication tables.

These nested for loops can be rewritten as:

Once you have written the loop in this form, converting it to a list comprehension is easy:

You can also use a similarly written list comprehension to flatten a list of lists. The outer for loop iterates through individual lists and stores them in the variable row. The inner for loop will then iterate through all the elements in the current row. During the first iteration, the variable row has the value [1, 2, 3, 4]. The second loop iterates through this list or row and appends all those values to the final list.

Nested List Comprehensions

Nested list comprehensions may sound similar to list comprehensions with nested loops, but they are very different. In the first case, you were dealing with loops within loops. In this case, you will be dealing with list comprehensions within list comprehensions. A good example of using nested list comprehensions would be creating a transpose of the matrix for the previous section.

Without a list comprehension expression, you will need to use two for loops to create the transpose.

The outer loop iterates through the matrix four times because there are four columns in it. The inner loop iterates through the elements inside the current row one index at a time and appends it to a temporary list called temp. The temp list is then appended as a row to the transposed matrix. In the case of nested list comprehensions, the outermost loop comes at the end and the innermost loop comes at the beginning. 

Here is the above code in the form of a list comprehension:

Another way to look at this is by considering the structure of list comprehensions that replace the basic for loops that you learned about at the beginning of the article.

If you compare it with the nested list comprehension above, you will see that <the_expression> in this case is actually another list comprehension: [row[n] for row in matrix]. This nested list comprehension itself is in the form of a basic for loop.

Final Thoughts

I hope this tutorial helped you understand what list comprehensions are and how to use them in place of basic for loops to write concise and slightly faster code while creating lists. 

Another thing that you should keep in mind is the readability of your code. Creating list comprehensions for nested loops will probably make the code less readable. In such cases, you can break down the list comprehension into multiple lines to improve readability.

Additionally, don’t hesitate to see what we have available for sale and for study on Envato Market, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.


No comments:

Post a Comment