List Comprehensions in 5-minutes
A visual introduction to those tricky Pythonic one-liners
Last updated
A visual introduction to those tricky Pythonic one-liners
Last updated
Just show me the code! Quick link: Jupyter Notebook on GitHub
Why would you want to do a Python list comprehension?
To save lines of code.
Thereâs might be more to it than that but in my experience, this is the only reason â if you have a better one, leave a comment and Iâll update the article.
You can get the exact same thing done with a couple extra lines. But browse any Python Stack Overflow question and chances are youâll find someone asking for a Pythonic version or a Pythonic one-liner.
List comprehensions are a way of achieving Pythonic one-liners with iterables (lists).
One-line definitions:
List = a Python object which can be iterated over (an iterable).
Iterated over = going through something one-by-one.
A good example is emptying your shopping cart at the cashier, you pull each item out one by one and put it on the counter, your shopping cart could be considered an iterable.
Weâll use this example to look at some code. Weâre shopping at a math store so all weâre buying is numbers.
What happened here?
We created a list of items in the cart
We created an empty cashier
list (the cashier
didnât have any of our items yet)
We used a for loop to iterate over each item
in our cart
For each item
we added it to the cashier list with .append()
Then we checked what items the cashier
had with print()
How could we do this same thing a list comprehension?
What happened here?
The exact same steps as above, only written in a different way. Letâs compare.A non-list comprehension and list comprehension comparison of the same code.
cashier
is created in blue. On the left, itâs created on its own line. On the right, itâs created at the same time everything else is being created.
cart
is being iterated over in green. item
is created as the for loop runs. This step is the same as grabbing one item
at a time out of your shopping cart and passing it to the cashier.
cashier
is updated in the red with each item
. The only difference is on the left, an .append()
statement is required. The list comprehension on the right negates the need for an .append()
statement
We accomplished the same steps in 1 line of code instead of 3. This may not seem like much but say you had a 1000 line Python project. You could potentially reduce your project from 1000 lines to 300. This kind of reduction wonât always happen but itâs an example of how to get the same task done with a Pythonic one-liner.
Now youâve got a little bit of an intuition, letâs look at a few more examples.
cashier_3
only deals with even numbers. How could we deal with this?
By using a conditional.
Conditional = another way of saying, do something if True, stop if False.
How about with a list comprehension?
Whatâs happening here?Example of a non-list comprehension and a list comprehension with a conditional.
This is similar to the above example except for the conditional in yellow.
cashier_3
is created in blue.
cart
is being iterated over in green. item
is being created as the for loop runs.
As each item
is passed to cashier_3
, itâs being checked to see if it matches up with the conditional in yellow.
cashier_3
is updated in the red with each item
as long as it fulfils the conditional in yellow.
cashier_4
only accepts numbers over 100 and are odd. How could you do this?
Now with a list comprehension.
This tutorial only scratches the surface of whatâs possible with Python list comprehensions. Once you start to get the hang of them, youâll start to realise how valuable they are for writing succinct and powerful Pythonic code.
If youâre looking for more, I recommend checking out the Python list comprehension tutorial on DataCamp.
All the code in this article is available on GitHub and a video version of this article is available on YouTube.
Reference : https://towardsdatascience.com/python-list-comprehensions-in-5-minutes-40a68cbe4561
In Python you can use list comprehensions to shorten the amount of code that you need to use to accomplish tasks when working with lists. The first time I heard of list comprehensions it sounded very advanced and confusing and when I looked at some example code I was, as I expected confused. Fear not list comprehensions are just as simple as a for loop and once you understand them you will begin to use them in your code to solve problems in much more elegant ways and conserving unneeded lines of code.
A list comprehension is a concept in Python thatâs used to generate a list. Its purpose is to allow a programmer to generate a list in a more fluent and efficient way and use less code in the process than if you were to use a for loop to generate a list. If you do not understand what a List is in python check out my post linked here to become more familiar with lists.
You can think of a list comprehension as a single line for loop enclosed in brackets (thats because it pretty much is) with the operation your performing coming first and the for loop statement coming second. Below I have a visual representation of a traditional for loop and where you place it in a list comprehension
As you can see the code in the blue square (the operation your performing) comes first inside the brackets and the code in the red square (for loop statement minus the colon â:â) comes second.
With this visual representation I hope it is easy to see that a list comprehension can be thought of as a reverse single line for loop.
Lets say we have a list of numbers and we need to add 5 to each of those numbers and print them out to the user. Below I have an example using a for loop to accomplish that task and then I solve the same problem using a list comprehension.
Now I will be the first to admit there are more elegant ways to solve this without the need to use 2 for loops, for instance I could have added print(number + 5) inside the first for loop to remove the need for a second for loop but at the same time I would be doing the math twice vs a second for loop. Now lets solve the same problem using a list comprehension.
Running both of the code snippets gives us the following output:
The mechanics of what is happening in both examples is almost the exact same the only exception is we are not creating a new list for the new numbers, instead the list comprehension at line 7 allows us to overwrite our existing list variable with the new values. We have reduced our total overall code by 5 lines but we still use 2 list comprehensions to first do the addition to each of the numbers and the second to print them to the user because we have kept our for loops to a single line.
Another useful way to use list comprehensions is when generating strings using values in a list, below I have an example based on the original one above to create a human readable string of the added numbers to display to the user that reads âMy following numbers are 7 and 10 and 21 and 25â
When using a for loop we have to create a new variable for the string, then we have to use a for loop to generate the custom part of our string (## and ## and etc.) then we need to remove the final and from the custom part of our string before we can finally print it to the user
Using a list comprehension we have shaved 8 lines off of our code and done all of the work in a single line. Now I will be the first to admit to understand the mechanics of what is happening here you need to analyze line 7 alittle harder but once you start getting comfortable reading more complex list comprehensions that one line it is easy to see what is happening.
Here is the breakdown of what is happening in line 7:
First the list comprehension is generating a new list and that list will contain the product of each of the numbers and 5 storing it as a string in the list that is being generated. That code is the list comprehension itself.
Second that list of strings is put together in the following format â## and ## and ## and ##â. That is done by using the join() method which has the list comprehension nested inside of it. Note the join() method is smart enough not to add the word âandâ after the last element in the list so we donât need to handle it like we did before.
At this point we have our custom string generated, formatted, and ready to be attached to the static part of our string.
Third our custom string is joined with the static part of our string by using the format() method with this code. (If you would like to understand more on string formatting check out my post linked here)
And finally it is printed out to the user by encasing all of that within a print statement.
Running both of the code snippets gives us the following output:
You can also nest list comprehensions much like you nest for loops so for instance if you have a list of lists and you need to run a list comprehension over each element in the nested lists this can be accomplished by using a list comprehension. Below I show you an example of adding 1 to each element in a list of lists, the first block I will show you using a for loop and the second i will show you using a list comprehension.
Running both of these code examples gives us the following result.
As you can see running each snippet of code they yield the same result but using a list comprehension takes off 8 lines of code that is the nested for loop and does everything in one line. Using the list comprehension we do not have to create any intermediate variables to count the number of loops or hold temporary data we simply re declare the same variable of our list âmylistâ and set it equal to the list comprehension and it takes care of all of the heavy lifting for us which allows us to have cleaner and more understandable code.
If understanding what is happening when translating a nested for loop into a list comprehension is hard for you to see below I have another visual representation as to where each part of the for loop goes into a list comprehension.
Looking at the picture we can see that in the list comprehension we have 2 sets of square brackets with the outer most of the for loop (red) in the outer most bracket, and the inner for loop (blue) inside the inner brackets with the operation we are performing (green) prepended to the beginning inside the inner brackets.
I hope that this article has cleared up any mystery with list comprehensions and I was able to provide some useful examples. If you have any questions please drop a comment below and I will be sure to get back to you with an answer as soon as possible and if this article was helpful please share on social media!
Reference : https://kyletk.com/index.php/2018/03/24/python-list-comprehensions/