Python Forum
basic question about tuples and immutability
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
basic question about tuples and immutability
#1
Hi there,

I have just been going through a basic sample bit of code designed to teach about tuples and dictionaries.

For completeness, please see the full bit of code below first of all. But not, that it is only a snippet of the code that I want to focus on. The code is an example of taking a series of students' names and their grades and then calculating the average grade for each student.

school_class = {}

while True:
    name = input("Enter the student's name (or type exit to stop): ")
    if name == 'exit':
        break
    
    score = int(input("Enter the student's score (0-10): "))
    
    if name in school_class:
        school_class[name] += (score,)
    else:
        school_class[name] = (score,)

print(school_class)

for name in sorted(school_class.keys()):
    adding = 0
    counter = 0
    for score in school_class[name]:
        adding += score
        counter += 1
    print(name, ":", adding / counter)
So the snippet I want to focus on is:

if name in school_class:
        school_class[name] += (score,)
    else:
        school_class[name] = (score,)
What is confusing me about this snippet is that the line
school_class[name] += (score,)
seems to be appending scores onto an already existing tuple. But I thought tuples were immutable and as such you would not be able to modify an already existing tuple.

Would someone be able to explain what I am misunderstanding here?
Reply


Messages In This Thread
basic question about tuples and immutability - by sudonym3 - Oct-18-2020, 01:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic Coding Question: Exit Program Command? RockBlok 3 617 Nov-19-2023, 06:31 PM
Last Post: deanhystad
  [solved] Basic question on list matchiing paul18fr 7 1,935 May-02-2022, 01:03 PM
Last Post: DeaD_EyE
  Very basic calculator question BoudewijnFunke 4 1,987 Dec-10-2021, 10:39 AM
Last Post: BoudewijnFunke
  Simple code question about lambda and tuples JasPyt 7 3,421 Oct-04-2021, 05:18 PM
Last Post: snippsat
  basic question isinstance tames 5 2,873 Nov-23-2020, 07:20 AM
Last Post: tames
  Basic Pyhton for Rhino 6 question about variables SaeedSH 1 2,167 Jan-28-2020, 04:33 AM
Last Post: Larz60+
  Basic Beginner question NHeav 4 2,838 Sep-13-2019, 11:43 AM
Last Post: NHeav
  Basic coding question with Python Than999 3 3,153 Jul-17-2019, 04:36 PM
Last Post: jefsummers
  basic question???????? cemdede 2 2,369 Jan-18-2019, 03:05 AM
Last Post: ntd9395
  basic plotting question Devilish 0 1,915 Dec-27-2018, 10:35 PM
Last Post: Devilish

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020