Reputation: 639
To illustrate my question, here is a minimal code.
x = [1,2,3]
y = ['a','b','c']
m = zip(x,y)
print(set(m))
print(set(m))
I expect the second print(set(m))
will generate the same result as the first print(set(m))
, but here is what we got...
{(1, 'a'), (2, 'b'), (3, 'c')}
set()
If we replace the set
to list
, the result is the same. Any suggestion on why this happen?
Upvotes: 3
Views: 301
Reputation: 4127
Since Python 3, zip now returns a iterator, not a list.
Your first set call 'unwinds' the iterator referenced by m (consumes it).
It is empty for the next call.
To solve this, use
m=list(zip(x,y)).
Upvotes: 6
Reputation: 430
Zip returns an iterator. We iterate through an iterator using the __next__
method. Once the items have been exhausted, it raises the stop iteration exception.
On your first call of the set
method, you exhaust the iterator. Therefore, when you make your second call to the iterator, there are no more items to iterate through, hence, returning an empty set.
Here's a link to how an iterator object is being implemented.
Upvotes: 2