Refactoring list-building code

suggest change

Suppose you have complex code that creates and returns a list by starting with a blank list and repeatedly appending to it:

def create():
    result = []
    # logic here...
    result.append(value) # possibly in several places
    # more logic...
    return result # possibly in several places

values = create()

When it’s not practical to replace the inner logic with a list comprehension, you can turn the entire function into a generator in-place, and then collect the results:

def create_gen():
    # logic...
    yield value
    # more logic
    return # not needed if at the end of the function, of course

values = list(create_gen())

If the logic is recursive, use yield from to include all the values from the recursive call in a “flattened” result:

def preorder_traversal(node):
    yield node.value
    for child in node.children:
        yield from preorder_traversal(child)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Generators:
* Refactoring list-building code

Table Of Contents
2 Filter
3 List
7 Loops
20 Generators
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve