I have run into a strange issue in Python 3.4.3, and it doesn't seem to be mentioned anywhere.
Lets say: a = [1,2,3,4]
and b = [5,6,7,8]
To concatenate these vertically: ab = zip(a,b)
in python 3, ab
itself would return:
zip object at (some hexnumber)
All well here, in python 3, to retrieve the concatenated list: aabb = list(ab)
Now heres the issue, first time, aabb
will indeed return a real list: [(1, 5), (2, 6), (3, 7), (4, 8)]
Second time and onwards however, if you do the whole process again list(aabb)
will simply return an empty []
container, just like list()
would do.
It will only work again after I restart shell/interpreter.
Is this normal or a bug?
EDIT: Ok guys I didn't realise it was to do with zip
, it SEEMED constant as ab
returned the same hex value everytime so I thought it was to do with list(ab)
.
Anyway, worked out by reassigning ab = zip(ab)
From what I understand in answers and original link, ab
gets disposed once read.
This problem will not be created by list(aabb)
but with list(ab)
in your code right now:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
ab = zip(a, b)
aabb = list(ab)
print(list(ab)) # -> []
The problem is that zip
is an iterator which stores values once and are then disposed like so:
ab = zip(a, b) # iterator created
aabb = list(ab) # elements read from ab, disposed, placed in a list
print(list(ab)) # now ab has nothing because it was exhausted
This on the other hand should work because aabb
is just a list, not the exhausted iterator ab
:
ab = zip(a, b)
aabb = list(ab)
print(list(aabb)) # -> [(1, 5), (2, 6), (3, 7), (4, 8)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With