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 seq
in the unix shell. If I run the following code:
a=range(10)
print(a)
The output is range(10)
, suggesting it's not a list but a different type of object. zip()
has a similar behaviour when printed, outputting something like
<zip object at "hexadecimal number">
So my question is what are they, what advantages are there to making them this, and how can I get their output to lists without looping over them?
You must be using Python 3.
In Python 2, the objects zip
and range
did behave as you were suggesting, returning lists. They were changed to generator-like objects which produce the elements on demand rather than expand an entire list into memory. One advantage was greater efficiency in their typical use-cases (e.g. iterating over them).
The "lazy" versions also exist in Python 2.x, but they have different names i.e. xrange
and itertools.izip
.
To retrieve all the output at once into a familiar list object, you may simply call list
to iterate and consume the contents:
>>> list(range(3))
[0, 1, 2]
>>> list(zip(range(3), 'abc'))
[(0, 'a'), (1, 'b'), (2, 'c')]