Skip to content

Instantly share code, notes, and snippets.

@ltfschoen
Created February 14, 2017 08:36
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 ltfschoen/ff9460d712c9aa8c70f934c809aef96c to your computer and use it in GitHub Desktop.
Save ltfschoen/ff9460d712c9aa8c70f934c809aef96c to your computer and use it in GitHub Desktop.
Python List Iterator Comparison Demo
# copy, paste, and execute this code in a python repl with python v2.7.12 or greater installed
import sys; assert sys.version_info >= (2,7,12)
# reimplement default repr function to return a module, name, and memory address of given object
def __repr__(self):
return '<%s.%s object at %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self))
)
# assume accepts array of numbers as parameters
def normalise_defensive(numbers):
print("list iterator at memory addresses: {}, {}".format( iter(nums), iter(nums) ) )
print("list iterator same id: {}, {}".format( id(iter(nums)), id(iter(nums)) ) )
print("list iterator memory addresses: {}, {}".format(iter(nums).__repr__(), iter(nums).__repr__()))
if iter(numbers) is iter(numbers): # An iterator -- bad!
# unreachable as iterators point to different memory addresses
raise TypeError('Must supply a container')
normalise_defensive([1,2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment