5

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.

DonD
  • 339
  • 3
  • 17
  • @vaultah i don't see anywhere in that section of the docs that `list(list(zip([1,2,3,4], [5,6,7,8]))) == []`. perhaps you can explain? @DonD, this is what you're saying you're getting? – abcd Apr 23 '15 at 16:30
  • 2
    Or http://stackoverflow.com/questions/3940072/exhausted-iterators-what-to-do-about-them – matsjoyce Apr 23 '15 at 16:31
  • @vaultah please elaborate, it doesn't say it why it works once only. and why was it downvoted soon as I posted it. – DonD Apr 23 '15 at 16:32
  • 1
    @vaultah The biggest problem is that `list(aabb)` doesn't return an empty list as the argument is a filled list not an empty iterator. The question states an incorrect problem without a full code sample. – Malik Brahimi Apr 23 '15 at 16:54
  • @dbliss That is a false statement. – Malik Brahimi Apr 23 '15 at 17:03

1 Answers1

4

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)]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70