Skip to content

Instantly share code, notes, and snippets.

@prendradjaja
Last active April 27, 2017 03:55
Show Gist options
  • Save prendradjaja/697cecc4e93a0efd010d2ea651c3db09 to your computer and use it in GitHub Desktop.
Save prendradjaja/697cecc4e93a0efd010d2ea651c3db09 to your computer and use it in GitHub Desktop.
An easy hole to fall into using Python iterators
# coding: utf-8
x = range(4)
y = zip('1234', 'abcd')
def has_four_unique_elements(seq):
return len(set(seq)) == 4
# This works fine.
print(1, has_four_unique_elements(x)) # -> True
# Still works fine.
print(2, has_four_unique_elements(x)) # -> True
print()
# This works too.
print(3, has_four_unique_elements(y)) # -> True
# ...but this doesn't.
print(4, has_four_unique_elements(y)) # -> False
print()
# Why? Because zips can only be used once. This makes sense, (if
# reusable, zip implementation would have to store whole seq) but it's
# easy to forget when you're writing something bigger with many
# iterators.
y = zip('1234', 'abcd')
print(5, list(y)) # -> [('1', 'a'), ('2', 'b')', ...]
print(6, list(y)) # -> []
print()
# In contrast, range is reusable:
print(7, list(x)) # -> [0, 1, 2, 3]
print(8, list(x)) # -> [0, 1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment