Python Forum

Full Version: basic question about tuples and immutability
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
You can't add or delete elements to tuple but, the existing elements can be modified if they are mutable type.

>>> tup = (1,'a',[1,2])
>>> tup[2][1] 
2
>>> tup[2][1] = 3
>>> tup
(1, 'a', [1, 3])
>>> tup[2].append(4)
>>> tup
(1, 'a', [1, 3, 4])
Here, the list in the tuple can be modified but not rest of the elements.
You can change existing items in list or add or delete items in List as it is mutable.
(Oct-18-2020, 01:50 PM)omm Wrote: [ -> ]You can't add or delete elements to tuple but, the existing elements can be modified if they are mutable type.

>>> tup = (1,'a',[1,2])
>>> tup[2][1] 
2
>>> tup[2][1] = 3
>>> tup
(1, 'a', [1, 3])
>>> tup[2].append(4)
>>> tup
(1, 'a', [1, 3, 4])
Here, the list in the tuple can be modified but not rest of the elements.
You can change existing items in list or add or delete items in List as it is mutable.

But in the initial example I gave, I believe school_list is a dictionary, and the keys this dictionary creates are the strings taken from the variable 'name' -- and the associated value for each of these keys is a tuple.

And what it looks like to me is that the line "school_class[name] += (score,)" is modifying an already existing value contained within the dictionary ... but since this value is of type tuple, I thought that wouldn't be possible.

The example you gave seems to be the other way around, where you are saying that for example you can modify a list contained within a tuple. But the initial example that I presented seems to be that a tuple is being modified that is contained within a dictionary.
The explanation is quite simple - tuples are immutable but here new object is created.

Simple illustration:

>>> a = (1, )
>>> id(a)
140560247802704
>>> a += (2, )
>>> a
(1, 2)
>>> id(a)
140560247791424
This is your current code output
Enter the student's name (or type exit to stop): one
Enter the student's score (0-10): 1
Enter the student's name (or type exit to stop): two
Enter the student's score (0-10): 2
Enter the student's name (or type exit to stop): one
Enter the student's score (0-10): 3
Enter the student's name (or type exit to stop): exit
{'one': (1, 3), 'two': (2,)}
one : 2.0
two : 2.0
Based on what I have browsed now "Since a tuple is immutable you have to build a new one and bind it to the key"
Can I know why are you using Tuple type as values. Is that intentional that you want to append a new number in tuple if you have same name? or do you want to just update.

I guess, I too need to play a little more with tuples in dictionary to understand better. I'll follow up to see more inputs from experts here.
(Oct-18-2020, 02:04 PM)sudonym3 Wrote: [ -> ]And what it looks like to me is that the line "school_class[name] += (score,)" is modifying an already existing value contained within the dictionary ... but since this value is of type tuple, I thought that wouldn't be possible.

It's not modifying the tuple in the dictionary. It's creating a new tuple and putting that in the dictionary in its place. The original tuple isn't modified. You can see this by either looking at the object id, or by making a copy of it.
(Oct-18-2020, 02:47 PM)omm Wrote: [ -> ]Can I know why are you using Tuple type as values. Is that intentional that you want to append a new number in tuple if you have same name? or do you want to just update.

The code I presented isn't my code. It was just an example piece of code that was presented in a learning resource that I am using that demonstrated use of both dictionaries and tuples.