1,105,331 Community Members

Tuple trouble

Member Avatar
Lardmeister
Posting Virtuoso
1,966 posts since Mar 2007
Reputation Points: 434 [?]
Q&As Helped to Solve: 111 [?]
Skill Endorsements: 8 [?]
 
0
 

Tuples are immutable objects, they cannot be changed says the Python manual.

my_tuple = (1, 2, 3, [4, 5, 6])

# this works
my_tuple[3][2] = 7

# clearly the item at index 3 in the tuple has changed
print(my_tuple)     # (1, 2, 3, [4, 5, 7])
Member Avatar
predator78
Junior Poster
168 posts since Sep 2008
Reputation Points: 22 [?]
Q&As Helped to Solve: 17 [?]
Skill Endorsements: 0 [?]
 
0
 

Think about the words though. Did you change the tuple? Or did you change the item at index of?

Member Avatar
woooee
Posting Maven
2,795 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
1
 

Lists are passed by reference, so the tuple contains the memory address of the list, not the list itself, and that doesn't change. Both of these statements will fail

my_tuple = (1, 2, 3, [4, 5, 6])

new_list = [4, 5, 6]
my_tuple[3] = new_list     ## new memory address
my_tuple[1] = "a"
Member Avatar
pyTony
pyMod
6,103 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

You are changing list, not tuple

>>> my_tuple
(1, 2, 3, [4, 5, 6])
>>> type(my_tuple[3])
<class 'list'>
>>> id(my_tuple[3])
14727328
>>> my_tuple[3][2]=7
>>> id(my_tuple[3])
14727328
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
1
 

Well, you are on to something, the tuple has changed. However, the id() of the whole tuple is still the same after the change.

My advice, don't rely blindly on tuples not changing as advertised.

Question Answered as of 2 Years Ago by pyTony, vegaseat, woooee and 1 other
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: