-2

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

Jaeho Song
  • 63
  • 1
  • 10
  • Learn to **search for error messages**. First results on google.. anyway, it has to do with Python 2 vs. 3 differences. zip used to return a list and now it does not. append is a member of a list. So the result of zip can be converted to a list to match Python 2 behavior, as in list(zip(..)), or a different method or concatenation can be used. – user2864740 Jul 18 '20 at 17:40
  • I think you should report this example to code academy. It looks like an effort was made to port it from python 2 to 3, but the porting is not complete. – tdelaney Jul 18 '20 at 18:01

4 Answers4

2

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)
J_H
  • 17,926
  • 4
  • 24
  • 44
Prune
  • 76,765
  • 14
  • 60
  • 81
  • Thank you, you got the point. I learned python2 first and learning 3 now. I think that is the reason why I wrote like that. Thank you again. I will accept your answer when the time limit is off – Jaeho Song Jul 18 '20 at 17:43
2

you should change zip to list:

gradebook = list(gradebook)
gradebook.append(("visual arts", 93))
abtinmo
  • 336
  • 2
  • 11
1

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

gradebook = list(zip(subjects, grades))
Kevin Mayo
  • 1,089
  • 6
  • 19
1

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