Python Gradebook - Append Zip List

Hi all,

Could someone explain to me what is the difference between

gradebook = list(zip(subjects, grades))
print(gradebook)

versus

gradebook = zip(subjects, grades)
print(list(gradebook))

Are they similar?

When I entered the latter syntax, gradebook = zip(subjects, grades) print(list(gradebook)) and then append it as follows: gradebook.append((‘Visual Arts’, 93)), then print(list(gradebook)), the output will return an error… Could someone explain why this is so please?

Thank you very much! :slight_smile:

zip objects are consumed on access. Consider,

>>> z = zip([1,2,3,4],[10,20,30,40])
>>> z.__next__()
(1, 10)
>>> z.__next__()
(2, 20)
>>> z.__next__()
(3, 30)
>>> z.__next__()
(4, 40)
>>> z.__next__()
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    z.__next__()
StopIteration
>>> 

When we cast a new list from a zip object, the object is completely consumed in the process…

>>> z = zip([1,2,3,4],[10,20,30,40])
>>> lz = list(z)
>>> z.__next__()
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    z.__next__()
StopIteration
>>> 

We can append to lz as much as we like, but we cannot append to z, since it has no append attribute.

>>> z
<zip object at 0x000001DCBE2C5F00>
>>> z.append((5, 50))
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    z.append((5, 50))
AttributeError: 'zip' object has no attribute 'append'
>>> lz.append((5, 50))

>>> lz
[(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)]
>>> 
1 Like