+ 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

3rd Dec 2020, 4:26 AM
Vitalij Bredun ♡ Python Petersburg
Vitalij Bredun ♡ Python Petersburg - avatar
7 Respostas
+ 3
Can you do c = list(zip(a,b)) and then just work with c?
3rd Dec 2020, 6:44 AM
David Ashton
David Ashton - avatar
+ 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
3rd Dec 2020, 11:11 AM
David Ashton
David Ashton - avatar
+ 2
`c` is a generator function you can only call `list(c)` once to get the list
3rd Dec 2020, 4:42 AM
o.gak
o.gak - avatar
+ 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.
3rd Dec 2020, 10:02 AM
o.gak
o.gak - avatar
+ 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?
3rd Dec 2020, 5:13 AM
Vitalij Bredun ♡ Python Petersburg
Vitalij Bredun ♡ Python Petersburg - avatar
+ 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
4th Dec 2020, 3:01 AM
John
John - avatar
0
David Ashton Thank you!! Your code will work but why my code don't work?
3rd Dec 2020, 7:31 AM
Vitalij Bredun ♡ Python Petersburg
Vitalij Bredun ♡ Python Petersburg - avatar