Recently I took a few moments to play around with some list comprehensions and document a few references that I would have found useful many months ago when I was first learning about and understanding them. Most recently I still didn’t fully understand the syntax when working with nested loops in a list comprehension, and so I took the time to write out some samples.
The basic pattern is as follows:
Here are some examples written out in both the non-python way across multiple lines and with a one-line list comprehension:
Starting with the most basic usage, we can copy the items in a list *(without using the copy function). Here we just use the basic pattern in a list comprehension to iterate over the items in a list.
Now we can apply the optional predicate wherein we supply a condition to determine whether or not an item should be included within the list itself.
This is not the same as adding conditional statements to determine the value placed in the list. In this example, the list size does not change, but the values added to the list are dynamic.
We can also include additional variables that are in scope within the list comprehension. If we enumerate a list, we can get each value’s corresponding index as well, and apply logic to use that index.
We can also build dictionaries with list comprehensions in Python 2.7 and above.
How the variables are used inside the list comprehension is up to you…
The above example is the reason I took the time to explore some examples. The syntax didn’t quite make sense to me, and every time I wanted to flatten a list I went and referenced a StackOverflow Question. However, it begins to make sense if we expand this out beyond two dimensions:
You’ll notice that the pattern here is to simply take all of your nested loops and just place them one after another without new spacing or line breaks. The rest of the syntax for the list comprehension obviously does not change.