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
#2
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.
Reply
#3
(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.
Reply
#4
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
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.
Reply
#6
(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.
sudonym3 likes this post
Reply
#7
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic Coding Question: Exit Program Command? RockBlok 3 584 Nov-19-2023, 06:31 PM
Last Post: deanhystad
  [solved] Basic question on list matchiing paul18fr 7 1,880 May-02-2022, 01:03 PM
Last Post: DeaD_EyE
  Very basic calculator question BoudewijnFunke 4 1,959 Dec-10-2021, 10:39 AM
Last Post: BoudewijnFunke
  Simple code question about lambda and tuples JasPyt 7 3,358 Oct-04-2021, 05:18 PM
Last Post: snippsat
  basic question isinstance tames 5 2,848 Nov-23-2020, 07:20 AM
Last Post: tames
  Basic Pyhton for Rhino 6 question about variables SaeedSH 1 2,157 Jan-28-2020, 04:33 AM
Last Post: Larz60+
  Basic Beginner question NHeav 4 2,792 Sep-13-2019, 11:43 AM
Last Post: NHeav
  Basic coding question with Python Than999 3 3,126 Jul-17-2019, 04:36 PM
Last Post: jefsummers
  basic question???????? cemdede 2 2,360 Jan-18-2019, 03:05 AM
Last Post: ntd9395
  basic plotting question Devilish 0 1,903 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