Title: Generator Expressions
Slug: generator_expressions
Summary: Generator Expressions in Python.
Date: 2016-01-23 12:00
Category: Python
Tags: Basics
Authors: Chris Albon

Interesting in learning more? Check out Fluent Python


In [1]:
# Create a list of students
students = ['Abe', 'Bob', 'Christina', 'Derek', 'Eleanor']

In [2]:
# Create a generator expression that yields lower-case versions of the student's names
lowercase_names = (student.lower() for student in students)

In [3]:
# View the generator object
lowercase_names


Out[3]:
<generator object <genexpr> at 0x104837518>

In [4]:
# Get the next name lower-cased
next(lowercase_names)


Out[4]:
'abe'

In [5]:
# Get the next name lower-cased
next(lowercase_names)


Out[5]:
'bob'

In [6]:
# Get the remaining names lower-cased
list(lowercase_names)


Out[6]:
['christina', 'derek', 'eleanor']