search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Python | Generators

schedule Aug 12, 2023
Last updated
local_offer
Python
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

While list comprehension returns a list (stored in memory), generators return a generator object (not stored in memory) that we can iterate over to produce elements of a list as required. Generator expressions look similar to list comprehension, however, use round brackets () rather than square brackets [].

NOTE

When working with small datasets you may not need to leverage generators as the data will comfortably fit in memory, however, when working with large datasets you will need to leverage generators as not all the data will be able to be stored in memory at once.

Examples

Basic usage

To create a generator object with values 0 to 4:

result = (num for num in range(5))
print(result)
<generator object <genexpr> at 0x7f8e5d36e4a0>

To iterate through the generator object and retrieve next element:

next(result)
0
NOTE

If we run next(result) again we will retrieve the next element in the generator object i.e. 1. We can continue running next(result) until there are no more elements left in the iterable, at which point a StopIteration error will be thrown.

Creating a list using generators

To create a list from a generator object:

result = (num for num in range(5))
list(result)
[0, 1, 2, 3, 4]

Conditionals

Similar to list comprehension, we can use conditionals in generator expressions:

odd_nums = (num for num in range(5) if num % 2 == 1)
list(odd_nums)
[1, 3]

Refer to list comprehension for more details on conditionals.

Generator function

A generator function uses the keyword yield instead of return for standard functions, which again produces a generator object:

def gen_values(n):
"""Generate values from 0 to n."""
i = 0
while i < n:
yield i
i += 1

Let us call gen_values and iterate over the resulting generator object:

gen_obj = gen_values(4)

for element in gen_obj:
print(element, end = " ")

Alternatively, we could have used the next() method to retrieve the next item in the iterable:

gen_obj = gen_values(4)
print(next(gen_obj))
0
NOTE

If we run next(result) again we will retrieve the next element in the generator object i.e. 1. We can continue running next(result) until there are no more elements left in the iterable, at which point a StopIteration error will be thrown.

robocat
Published by Arthur Yanagisawa
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!