Reputation: 187
a=b=range(3)
In[1] = zip(a,b)
I expect to see something like this:
out[1] =
[(0 0),
(1 1),
(2 2)]
however, the output i get is:
out[1] = <zip at 0x26da8d2e9c8>
The same for other functions, f.i.
range(20)
out = range(0,20))
For these function this is not a problem, because I know how these work. But it makes it hard to play around with function and understand how they work because you can never see the output.
Can someone explain to me why this console works like this and how I can change this?
Upvotes: 1
Views: 326
Reputation: 20434
Convert them to lists:
>>> list(zip(a,b))
[(0, 0), (1, 1), (2, 2)]
The reason you need to do this is because zip()
returns an iterator (something you can call next()
on) and range()
returns an iterable (something you can call iter()
on). Both of which are not evaluated before they are needed to be (they are "lazy" in this sense) so they do not display all their contents when assigned to variables.
However, when you convert them into lists, they are iterated over and evaluated so you can see their contents.
The same is true when you create your own iterable or iterator:
class my_iterator():
def __init__(self):
self.x = 0
def __iter__(self):
return self
def __next__(self):
self.x += 1
if self.x < 10: return self.x
raise StopIteration
which then performs in a very similar fashion to zip
instances:
>>> i
<__main__.my_iterator object at 0x7f219d303518>
>>> list(i)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Upvotes: 1