Skip to content

Instantly share code, notes, and snippets.

@loisaidasam
Last active February 15, 2017 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loisaidasam/2d3e544029562a30f097b89beb87f6c9 to your computer and use it in GitHub Desktop.
Save loisaidasam/2d3e544029562a30f097b89beb87f6c9 to your computer and use it in GitHub Desktop.
TIL about mutable python generator data
"""
TIL data used/returned in python generators doesn't have any special mutability
properties - they're just like the rest of us!
"""
In [1]: def generator():
...: result = [1, 2, 3, 4]
...: while True:
...: print "before", result
...: yield result
...: print "after", result
...:
In [2]: gen = generator()
In [3]: data = gen.next()
before [1, 2, 3, 4]
In [4]: data
Out[4]: [1, 2, 3, 4]
In [5]: data.append(5)
In [6]: data
Out[6]: [1, 2, 3, 4, 5]
In [7]: gen.next()
after [1, 2, 3, 4, 5]
before [1, 2, 3, 4, 5]
Out[7]: [1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment