## ๐Ÿงต [Python] Why `zip(*zipped)` sometimes works twice, and sometimes doesn't?

Yeeunยท2025๋…„ 4์›” 14์ผ

Python

๋ชฉ๋ก ๋ณด๊ธฐ
4/31

๐Ÿงต [Python] Why zip(*zipped) sometimes works twice, and sometimes doesn't?

In Python, I recently came across this confusing behavior:

zipped = [(1, 'a'), (2, 'b'), (3, 'c')]
unzipped = zip(*zipped)

t1, t2 = map(list, unzipped)
list1, list2 = map(tuple, unzipped)  # โŒ Error: already consumed!

But in another case:

zipped = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, names = zip(*zipped)

for num, name in zip(numbers, names):
    print(f"num={num}, name={name}")  # โœ… Works

The second example works twice, even though it also uses zip(*zipped)? Why?

Letโ€™s break it down ๐Ÿ‘‡


๐Ÿ”„ zip returns an iterator

unzipped = zip(*zipped)

This doesnโ€™t give you a list or a tuple โ€” it gives you a zip iterator, which is like a one-time-use stream. Once you read from it (like using map(), for, or list()), it's consumed and cannot be reused.

unzipped = zip(*zipped)
print(list(unzipped))  # โœ… Works
print(list(unzipped))  # โŒ Empty: already used

๐Ÿ’ก Solution 1: Wrap it with list() or tuple()

To reuse the result, convert the zip object to a list (or tuple) right away:

unzipped = list(zip(*zipped))

t1, t2 = map(list, unzipped)
list1, list2 = map(tuple, unzipped)  # โœ… Now it works!

๐Ÿ’ก Solution 2: Unpack immediately

This is what makes the second example work:

numbers, names = zip(*zipped)

Hereโ€™s whatโ€™s really happening:

  • zip(*zipped) creates a one-time-use zip object.
  • The unpacking (numbers, names = ...) forces the iterator to run immediately.
  • The values are saved as reusable tuples.

So:

print(numbers)  # (1, 2, 3)
print(names)    # ('a', 'b', 'c')

You can reuse numbers and names as many times as you want.


๐Ÿง  Summary

CaseTypeReusable?
zip(*zipped)zip iteratorโŒ No
list(zip(*zipped))listโœ… Yes
numbers, names = zip(*zipped)tuple unpackโœ… Yes

๐Ÿฏ Analogy

Think of zip(*zipped) like a stream of water.

  • If you read from it once, it's gone.
  • But if you store it in a bottle (like a list or tuple), you can drink from it anytime. ๐Ÿ˜Š

Let me know if this helped you understand zip and unpacking better!
If you found this post useful, feel free to leave a like ๐Ÿ’›

0๊ฐœ์˜ ๋Œ“๊ธ€