0

I seem to have found out a weird bug in Python and I do not know if it exists already or is it something wrong that I am doing. Please explain.

We know that we can zip two lists in python to combine them as tuples. We can again parse them easily. When I am trying to parse the same zipped variable more than once, Python doesnt seem to be doing that and it ends up giving empty lists []. The first time it will do it but more than once it wont.

Example:

lis1=[1,2,3,4,5]
lis2=['a','b','a','b','a']
zip_variable=zip(lis1,lis2)
op1=[val2 for (val1,val2) in zip_variable if val1<4]
op2=[val1 for (val1,val2) in zip_variable if val2=='a']
op3=[val1 for (val1,val2) in zip_variable if val2=='b']
print(op1,"\n",op2,"\n",op3)

Output:

['a','b','a']
[]
[]

I have the solution to fix it which is by making multiple variables for the same zip i.e as below:

lis1=[1,2,3,4,5]
lis2=['a','b','a','b','a']
zip_variable1=zip(lis1,lis2)
zip_variable2=zip(lis1,lis2)
zip_variable3=zip(lis1,lis2)
op1=[val2 for (val1,val2) in zip_variable1 if val1<4]
op2=[val1 for (val1,val2) in zip_variable2 if val2=='a']
op3=[val1 for (val1,val2) in zip_variable3 if val2=='b']
print(op1,"\n",op2,"\n",op3)

Output:

['a','b','a']
[1,3,5]
[2,4]

The solution is always possible if we dont care about memory.

But the main question why does this happen?

munnahbaba
  • 231
  • 1
  • 3
  • 10

2 Answers2

4

zip() returns an iterator in Python 3. It produces only one tuple at a time from the source iterables, as needed, and when those have been iterated over, zip() has nothing more to yield. This approach reduces memory needs and can improve performance as well (especially if you don't actually ever request all the zipped tuples).

If you need the same sequence again, either call zip() again, or convert zip() to a list like list(zip(...)).

You could also use itertools.tee() to create "copies" of a zip() iterator. However, behind the scenes, this stores any items that haven't been requested by all iterators. If you're going to do that, you might as well just use a list to begin with.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

Because zip function returns an iterator. This kind of object can only be iterated once.

If you want to iterate multiple times the same zip I recomend you creating a list or a tuple from it (list(zip(a, b)) or tuple(zip(a, b)))

Yadkee
  • 66
  • 1
  • 5