1

I'm messing around with zipping 3 lists together and then unpacking them in Python to better understand lists and zip(). In the code below, if I don't comment out print(list(zip_list)), the unzip1-3 variables produce empty lists. If i do comment that part out, i get the lists I would expect. Why would this be?

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['!', '@', '#']

zip_list = zip(list1, list2, list3)
print(list(zip_list))

unzip1 = []
unzip2 = []
unzip3 = []

for i, j, k in zip_list:
    unzip1.append(i)
    unzip2.append(j)
    unzip3.append(k)

print(unzip1)
print(unzip2)
print(unzip3)

Output:

[(1, 'a', '!'), (2, 'b', '@'), (3, 'c', '#')]
[]
[]
[]

Output, commented out:

[1, 2, 3]
['a', 'b', 'c']
['!', '@', '#']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
dele2111
  • 11
  • 1
  • 1
    Note that `zip` is a generator, and `list(zip_list)` consumes it, thus, your iterator is empty afterwards – C.Nivs Sep 13 '20 at 22:35
  • @C.Nivs To be pedantic, it's an iterator but not a generator – wjandrea Sep 13 '20 at 22:41
  • @C.Nivs - that does! I didn’t realize that .zip() didn’t just create a new list. It makes sense that the statement basically clears the iterator – dele2111 Sep 13 '20 at 22:46
  • Can I ask, why would we only want to use the iterator once? I’m obviously new to this, but what is the thought behind “consuming” the iterator only once? – dele2111 Sep 13 '20 at 23:01
  • @dele2111 See [Performance Advantages to Iterators?](https://stackoverflow.com/q/628903/4518341) tl;dr it's more efficient for large amounts of data – wjandrea Sep 13 '20 at 23:21
  • Ok that makes sense. Basically if we have a large set it's better to just iterate and get our result than to do that plus store that data in a list. I think as a beginner I am focused solely on syntax and not necessarily on application. Thanks for your help! – dele2111 Sep 13 '20 at 23:25

0 Answers0