Python 3 side effects of list?

Question:

I’m new to python and was testing unzipping (because I read it didn’t work in python 3). But found this strange thing:

l1="abcd"
l2="1234"
zipped=zip(l1,l2)
#print(l1,l2,list(zipped))
l1,l2=zip(*zipped)
print(l1,l2)

prints ('a', 'b', 'c', 'd') ('1', '2', '3', '4')

but

l1="abcd"
l2="1234"
zipped=zip(l1,l2)
print(l1,l2,list(zipped))
l1,l2=zip(*zipped)
print(l1,l2)

creates an error: Traceback (most recent call last):
File "python", line 5, in <module>
ValueError: not enough values to unpack (expected 2, got 0)

But I didn’t even change line 5 nor did I reassign zipped. All I can thing of is that list has some weird unexpected side effect. Could someone more experienced clear this up?

EDIT: I checked if list turns the zip object into a list by inserting an extra print(zipped) but it printed <zip object at 0x7f993c85af48>. I now suspect it has some thing to do with repl.it.

Asked By: fejfo

||

Answers:

list(zipped) iterates over zipped, so when you do l1, l2 = zip(*zipped), zipped is empty, so you just do l1, l2 = zip(), and zip() returns an empty generator of length 0, when you expect 2 (l1, l2).

Answered By: internet_user

zip in Python 3 changed to become a generator, meaning it will not produce a potentially huge list of results immediately, but instead one-by-one. The upshot is: less memory usage. The downside: you exhaust your generator by calling list(…) around it, because that consumes all the produced elements. Hence the error. Pass the generated list to the next line if you care.

Answered By: deets
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.