I understand how functions like range()
and zip()
can be used in a for loop. However I expected range()
to output a list - much like <
Range (xrange
in python 2.*) objects are immutable sequences, while zip (itertools.izip
repectively) is a generator object. To make a list from a generator or a sequence, simply cast to list. For example:
>>> x = range(10)
>>> list(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
But they differ in a way how elements are generated. Normal generators are mutable and exaust their content if iterated, while range is immutable, and don't:
>>> list(x) # x is a range-object
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # second cast to list, contents is the same
>>> y = zip('abc', 'abc')
>>> list(y) # y is a generator
[('a', 'a'), ('b', 'b'), ('c', 'c')]
>>> list(y)
[] # second cast to list, content is empty!