itertools
More efficient versions of built-in functions
Other very useful functionality
- chain - combine multiple iterables to look like one
- count - just like our counter (but without stop or by arguments)
- repeat - return the given argument repeatedly
- more...
Combining multiple itertools functions
numbers = "zero one two three".split()
for number, word in izip(count(), numbers):
print "%d = %s" % (number, word)
# Result:
# 0 = zero
# 1 = one
# 2 = two
# 3 = three
for number, word in izip(xrange(10), chain(numbers, repeat("unknown"))):
print "%d = %s" % (number, word)
# Result:
# 0 = zero
# 1 = one
# 2 = two
# 3 = three
# 4 = unknown
# 5 = unknown
# 6 = unknown
# 7 = unknown
# 8 = unknown
# 9 = unknown
Combining it all