Understanding Python List Comprehensions
Coming to Python from other programming languages, I struggled at first to decipher list comprehensions.
List comprehensions let you turn these three lines of code:
into this:
Well, it’s certainly shorter but it can also be a bit overwhelming to process at first. How exactly do I interpret all of the different occurrences of thing(s) in that line??
Breaking down the creation of List Comprehensions
Let’s say you have a list of prices and want to find the cheap prices (under $10)
things=[10.34,98.45,78.56, 5.43,100.5, 4]
If you’re comfortable with For Loops, you could easily build out this logic:
cheap_things=[]
for thing in things:
if thing < 10:
cheap_things.append(thing)
cheap_things>> [5.43, 4]
But how do you turn that into a list comprehension? Once someone showed the following approach, it suddenly made sense to me. So, here we go…
- Create an empty list: []
[]
- Create the basic For Loop inside those brackets
[for thing in things]
- Put the action you want to take BEFORE the For Loop. In this case, we want to grab the value of thing (one price in our list)
[thing for thing in things]
- If you want to put any conditions or restrictions on what elements of the list are grabbed/acted on, put those conditions AFTER the for loop (we only want to grab the price IF it is less than $10)
cheap_things=[thing for thing in things if thing < 10]
- Finally, you’ve now created a new list and so you need to assign it to something (save it to our cheap_things list)
cheap_things=[thing for thing in things if thing < 10]
cheap_things>> [5.43, 4]
Putting it all together, the pieces slide around like so: