Generator-Related Topics in Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This section introduces a few additional generator related topics including generator expressions and the itertools module.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("`Raising Exceptions`") python/FileHandlingGroup -.-> python/file_opening_closing("`Opening and Closing Files`") python/AdvancedTopicsGroup -.-> python/generators("`Generators`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/PythonStandardLibraryGroup -.-> python/os_system("`Operating System and System`") python/BasicConceptsGroup -.-> python/python_shell("`Python Shell`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/variables_data_types -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/numeric_types -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/strings -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/conditional_statements -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/for_loops -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/list_comprehensions -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/lists -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/tuples -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/dictionaries -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/function_definition -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/importing_modules -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/using_packages -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/standard_libraries -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/classes_objects -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/constructor -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/polymorphism -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/encapsulation -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/raising_exceptions -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/file_opening_closing -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/generators -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/data_collections -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/os_system -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/python_shell -.-> lab-132729{{"`Generator-Related Topics in Python`"}} python/build_in_functions -.-> lab-132729{{"`Generator-Related Topics in Python`"}} end

Generator Expressions

A generator version of a list comprehension.

>>> a = [1,2,3,4]
>>> b = (2*x for x in a)
>>> b
<generator object at 0x58760>
>>> for i in b:
...   print(i, end=' ')
...
2 4 6 8
>>>

Differences with List Comprehensions.

  • Does not construct a list.
  • Only useful purpose is iteration.
  • Once consumed, can't be reused.

General syntax.

(<expression> for i in s if <conditional>)

It can also serve as a function argument.

sum(x*x for x in a)

It can be applied to any iterable.

>>> a = [1,2,3,4]
>>> b = (x*x for x in a)
>>> c = (-x for x in b)
>>> for i in c:
...   print(i, end=' ')
...
-1 -4 -9 -16
>>>

The main use of generator expressions is in code that performs some calculation on a sequence, but only uses the result once. For example, strip all comments from a file.

f = open('somefile.txt')
lines = (line for line in f if not line.startswith('#'))
for line in lines:
    ...
f.close()

With generators, the code runs faster and uses little memory. It's like a filter applied to a stream.

Why Generators

  • Many problems are much more clearly expressed in terms of iteration.
    • Looping over a collection of items and performing some kind of operation (searching, replacing, modifying, etc.).
    • Processing pipelines can be applied to a wide range of data processing problems.
  • Better memory efficiency.
    • Only produce values when needed.
    • Contrast to constructing giant lists.
    • Can operate on streaming data
  • Generators encourage code reuse
    • Separates the iteration from code that uses the iteration
    • You can build a toolbox of interesting iteration functions and mix-n-match.

itertools module

The itertools is a library module with various functions designed to help with iterators/generators.

itertools.chain(s1,s2)
itertools.count(n)
itertools.cycle(s)
itertools.dropwhile(predicate, s)
itertools.groupby(s)
itertools.ifilter(predicate, s)
itertools.imap(function, s1, ... sN)
itertools.repeat(s, n)
itertools.tee(s, ncopies)
itertools.izip(s1, ... , sN)

All functions process data iteratively. They implement various kinds of iteration patterns.

More information at Generator Tricks for Systems Programmers tutorial from PyCon '08.

In the previous exercises, you wrote some code that followed lines being written to a log file and parsed them into a sequence of rows. This exercise continues to build upon that. Make sure the stocksim.py is still running.

Exercise 6.13: Generator Expressions

Generator expressions are a generator version of a list comprehension. For example:

>>> nums = [1, 2, 3, 4, 5]
>>> squares = (x*x for x in nums)
>>> squares
<generator object <genexpr> at 0x109207e60>
>>> for n in squares:
...     print(n)
...
1
4
9
16
25

Unlike a list a comprehension, a generator expression can only be used once. Thus, if you try another for-loop, you get nothing:

>>> for n in squares:
...     print(n)
...
>>>

Exercise 6.14: Generator Expressions in Function Arguments

Generator expressions are sometimes placed into function arguments. It looks a little weird at first, but try this experiment:

>>> nums = [1,2,3,4,5]
>>> sum([x*x for x in nums])    ## A list comprehension
55
>>> sum(x*x for x in nums)      ## A generator expression
55
>>>

In the above example, the second version using generators would use significantly less memory if a large list was being manipulated.

In your portfolio.py file, you performed a few calculations involving list comprehensions. Try replacing these with generator expressions.

Exercise 6.15: Code simplification

Generators expressions are often a useful replacement for small generator functions. For example, instead of writing a function like this:

def filter_symbols(rows, names):
    for row in rows:
        if row['name'] in names:
            yield row

You could write something like this:

rows = (row for row in rows if row['name'] in names)

Modify the ticker.py program to use generator expressions as appropriate.

Summary

Congratulations! You have completed the More Generators lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like