Filtering III: Generalized Template
In this lesson, you saw the benefit of what we did in the previous lessons where we broke the list comprehensions down and transformed them into traditional for
loops. Doing this helped to make it easier to grasp them.
You also saw a generalized pattern for writing for
loops with filtering:
values = [expression for value in collection if condition]
values = []
for value in collection:
if condition:
values.append(expression)
00:00
All right, so I’ve got the updated template here, and pretty much all that I’ve added is this if condition
part. We can take a look at how this would transform to a for
loop.
00:12
All right, and this is how it would transform into a for
loop. So again, this is really similar to the previous template, but now we’ve added this if condition:
line that applies the filtering.
00:23
So you can see, if you build your understanding of list comprehensions step-by-step, then I think it becomes much easier to actually see what’s going on. Because the jump from the previous list comprehension and then adding this if condition
here is relatively small.
00:38
It’s relatively easy to wrap your head around that. But if you’ve seen that for the first time, if you had seen a more complex list comprehension—you know, like this one—it would seem a little bit overwhelming, to be honest, because it just helps to break things down into these little steps, and hopefully that example showed you how these list comprehensions break down into these relatively simple for
loops.
Become a Member to join the conversation.