Populating Lists From Scratch in List Comprehensions
In the last lesson, you saw how to populate a list using the
.append() method inside a
for loop. That’s a very important programming structure. In fact, we’ll come back to that in the next lesson.
But Python has developed a syntax called a list comprehension, which simplifies the code needed to perform that same action. It doesn’t use
.append() at all, but it’s important enough that you really should see it in this course while you’re looking at how to populate lists.
Here’s what that same function would look like using a list comprehension. The first thing you notice is the absence of a
for loop. List comprehension syntax does the iteration for you automatically.
You begin with an expression in brackets, the brackets indicating that you’re creating a list. The first thing inside the brackets is a model of what each expression in the list should look like. And here, since we’re taking the square root of a number, you see the same expression that you saw in the
.append() statement in the previous version.
And we can see the same results. List comprehensions are really great. They give you a short, concise way to build a list. But there are times when you really do need to use a
for loop, and that’s if you want to do additional processing inside the loop while you populate the list.
Become a Member to join the conversation.