Extract Even Numbers With a Generator
00:21 When Python programmers talk about generators, they either mean generator functions or generator expressions. In this lesson, you’ll work with generator expressions, but I’ll add you a resource that covers generator functions at the end of this course if you want to learn more about them. Okay, now let’s go ahead and talk about generator expressions.
01:02 Generator expressions are created using a syntax similar to list comprehensions, but with parentheses instead of square brackets. And they use lazy evaluation, meaning they generate values on the fly as they’re needed.
You have the same exact generator expression here:
(number ** 2 for number in range(1, 5)), not including
5. And this generator expression is stored in
squares. Okay, so this generator expression is not immediately executed or evaluated.
Extract even numbers using a generator. You’ve already done this multiple times, and you’re familiar how to do this with
filter(). Your goal is to replace
filter() with a generator expression to filter out the odd numbers and keep the even ones.
You’re using the same list of numbers from the previous times you extracted even values,
numbers = [1, 3, 10, 45, 6, 50]. Your filtering condition is the same, so you can use the same predicate function,
numberas an input.
return number % 2 == 0.
It doesn’t really make a difference. At the end, you get the same results,
50. You just successfully replaced the
filter() function with a generator expression and extracted the even numbers of a list.
Become a Member to join the conversation.