search
Search
Publish
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
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
A
A
share
thumb_up_alt
bookmark
arrow_backShare
Twitter
Facebook

Python | Generators

Programming
chevron_right
Python
chevron_right
Operations
chevron_right
List Operations
chevron_right
Documentation
schedule Mar 10, 2022
Last updated
local_offer Python
Tags

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
Ask a question or leave a feedback...