Skip to content

Instantly share code, notes, and snippets.

@matthieubulte
Created November 29, 2014 20:32
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 matthieubulte/b78d6555eb1201368594 to your computer and use it in GitHub Desktop.
Save matthieubulte/b78d6555eb1201368594 to your computer and use it in GitHub Desktop.
LazyList
class LazyList():
def __init__(self, iterable):
self._list = []
self._iterable = iter(iterable)
self._has_thrown = False
self._current_index = 0
def __iter__(self):
return self
def _cached_next(self):
if self._current_index >= len(self._list):
raise StopIteration()
else:
index = self._current_index
self._current_index += 1
return self._list[index]
def _uncached_next(self):
_next = self._iterable.next()
self._list.append(_next)
return _next
def next(self):
try:
return self._cached_next() if self._has_thrown else self._uncached_next()
except StopIteration:
self._has_thrown = True
self._current_index = 0
raise StopIteration()
y = LazyList((a*a for a in [1, 2, 3, 4]))
# y = LazyList([1, 4, 9, 16])
for x in y:
print x**2
for x in y:
print x**3
for x in y:
print x**4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment