+ 2
[SOLVED] d == [(1,3),(2,4)] Why list index out of range d[0]? zip
a=[1,2] b=[3,4] c=zip(a,b) print(c) print(list(c)) d=list(c) # [(1,3),(2,4)] d[0] # Why list index out of range? # Why len(d)==0 ? https://code.sololearn.com/c3m6A7qBZL1z/?ref=app
7 Réponses
+ 3
Can you do c = list(zip(a,b)) and then just work with c?
+ 3
Vitalij Bredun ♡ JUMP_LINK__&&__Python__&&__JUMP_LINK Petersburg zip() produces a zip object which is an iterator, which as o.gak suggested can only be iterated once and then it is exhausted. This is the same with generator expressions. This code will demonstrate:
https://code.sololearn.com/c2h7EEX11Jt7
+ 2
`c` is a generator function
you can only call `list(c)` once to get the list
+ 2
`zip` will return a generator function (it is `c` in your code).
When you call `list(c)` for the 1st time, it will generate the `zip` result and push them into a list as you want.
But if you call `list(c)` again, the generation is over so nothing will be generated and end with an empty list.
So if you want a list returned by `zip`, just as David Ashton said, use `list(zip(a, b))` then the code will be ok.
+ 1
o.gak Thank you! But if i get list then i hope to work with list.
type(d) # Class "list"
len(d) # 0. Why?
+ 1
when you put the zip object (c in your case) in the constructor of the list class, it is iterated over to convert it to a list.Now, since the zip object is a generator under the hood, it will yield values when iterated over and its values are exhausted.When you the try to assign d = list(c), c has no values left and therefore d is assigned an empty list
0
David Ashton Thank you!! Your code will work but why my code don't work?