1

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.

fejfo
  • 217
  • 1
  • 7

2 Answers2

2

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.

deets
  • 6,285
  • 29
  • 28
0

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).

internet_user
  • 3,149
  • 1
  • 20
  • 29