+ 1

Tuples are immutable!

Tuples are immutable! hi guys, plz help me out myTuple=('reza', 'shah',['item1','item2']) myList=myTuple [2] myList.append('item3') and now myTuple has been changed!!! wtf...?

25th Nov 2017, 3:24 PM
reza
reza - avatar
4 odpowiedzi
+ 5
Because index[2] of tuple is list and list is mutable. It is why myTuple is changed
25th Nov 2017, 3:36 PM
Ferhat Sevim
Ferhat Sevim - avatar
+ 2
line 2: When you said "myList=myTuple[2]", you told python that the variable "myList" references/points to the element inside the title at index 2, which is the list. When you added an item to your list, you changed the size of the list, but not the tuple itself. The tuple doesn't count how many items it has plus the ones inside the list. it counts the list itself as a single element. You can test this yourself by typing: print (len (myTuple) )
25th Nov 2017, 3:35 PM
Sapphire
+ 1
A tuple is immutable. it starts with 3 items and they cannot be changed. This rule still applies to lists and dictionaries, but the tuple doesn't actually store them, but points to them. It doesn't know what is inside the list or dictionary. Therefore the size of those lists or dictionaries can change size.
25th Nov 2017, 3:52 PM
Sapphire
0
what I'm saying is why myTuple (before Channing myTuple [2]) = myTuple (after Channing myTuple [2]) this is kinda confusing for me!
25th Nov 2017, 3:44 PM
reza
reza - avatar