Create List Comprehensions
Often you might want to perform an action on each element in a collection. So let’s start off by creating a collection. Again, I will make a
(1, 2, 3), and this could be a list as well.
You can do this using a
for loop, and then you need to also collect the values that you calculated somewhere. A common way of doing that is by first creating an empty list and then collecting all the calculated values in there.
Then I want to append to
squares. So I’ll say
squares.append() and I want to append the result of the calculation. So here I want to raise
num to the power of
2, which in Python you can do by, in this case, writing
01:45 And using this construct works and is perfectly fine, but it’s quite a lot of code to write. And because these types of calculations are quite common, Python has a different construct for it that’s called a list comprehension.
Now you can, instead of writing these three lines of code, starting off with the initialization of the empty list and then ending with the calculation inside of the
for loop, you can do all of that in a single line.
Start off by giving a variable name to the list you want to create. And then again, I make an empty list basically. But now instead of sticking with it as an empty list, I’m going to piece into these square brackets the pieces of the
And here you again see the
for loop that you’ve seen over in IDLE as well. The construct is that you start off with initializing an empty list, then say
for <element> in <collection>:, and then you do your operations where you append to the empty list that you created before the result of a calculation.
And the same thing works when you take first the calculation again inside of square brackets and then say
for num in numbers, so the syntax you use for starting a
for loop, after the calculation that you want to perform wrapped inside of square brackets.
This is what a list comprehension is, and it gives you the same results as using the
for loop. And the result is going to be a list of course, because you’re wrapping this in square brackets here.
04:18 This is what list comprehensions are and how they work. I hope making this connection to for loops helps you to understand what they are and how you can use them to write sometimes more concise code.
04:39 All right, with list comprehensions as part of your tool belt, let’s next look at how you can nest and copy lists. But because nothing sinks in without training, I’ve got a couple of review exercises for you first that you can choose to tackle if you want to.
Become a Member to join the conversation.