python: append() into zip() problem. 'zip' object has no attribute 'append'

3.6k Views Asked by At

Hope your days are going well :)

I am learning python recently with code academy site, and they gave me an example about zip() and append().

last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)]
subjects = ["physics", "calculus", "poetry", "history"]
grades = [98, 97, 85, 88]
subjects.append("computer science")
grades.append(100)
gradebook = zip(subjects, grades)

#This code is the problem
gradebook.append(("visual arts", 93))

print(list(gradebook))

This is the code I made but it gives me an error.

Traceback (most recent call last):
  File "script.py", line 9, in <module>
    gradebook.append(("visual arts", 93))
AttributeError: 'zip' object has no attribute 'append'

I would search for the error first for normal case, but the problem is, the code I wrote is exactly same as the code they gave me as an solution. That is why I am confused and asking here. Is it the error of the site or the solution is wrong?

Thank you for your attention

4

There are 4 best solutions below

1
On BEST ANSWER

The problem is that zip is an iterator, not a sequence. I suspect that you have some old or untested code, not compatible with the current Python version. You zip result is usable as the target of a for statement, but has no append attribute -- it's a special type of function.

The conversion is easy enough: make a list from it earlier:

gradebook = list(zip(subjects, grades))

#This code is the problem
gradebook.append(("visual arts", 93))

print(gradebook)
1
On

Because gradebook is a zip object. You may need to use

gradebook = list(zip(subjects, grades))
0
On

you should change zip to list:

gradebook = list(gradebook)
gradebook.append(("visual arts", 93))
1
On

Here "gradebook = zip(subjects, grades) " you are creating a zip instance but in order to appen something you need to make it a list using list function like this gradebook = list(zip(subjects, grades) )