Filtering II: For Loop Example
This lesson continued the discussion on filtering, this time using a for
loop to generate a list of squares. The for
loop does exactly what the list comprehension from the last lesson did and the output is the same.
You saw that, using a for
loop, the code turns out this way:
>>> even_squares = []
>>> for x in range(10):
... if x % 2 == 0:
... even_squares.append(x * x)
00:00
So, if you wanted to generate the same list with a for
loop, you would probably do something like this. Again, you would start out by creating an empty output list, and then we would iterate over this range again.
00:13
And now what we need to add is the filtering. So in this case, I would just add the filtering condition here, inside the for
loop,
00:24
and then if the filter condition is True
, only then am I going to append the calculated value to my output list. This is exactly what I’ve done here, so hopefully, we’ll get the same result. Yup—that looks pretty good.
00:39
You can see here how I took the initial list comprehension with filtering and transformed it into an equivalent for
loop.
Become a Member to join the conversation.