Tuple trouble
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])
Related Article: Just need a little python help please!!!
is a Python discussion thread by ronparker that has 1 reply, was last updated 2 years ago and has been tagged with the keywords: excel, mysql, numbers, python.
Lardmeister
Posting Virtuoso
1,939 posts since Mar 2007
Reputation Points: 465
Solved Threads: 72
Skill Endorsements: 5
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"
woooee
Posting Maven
2,707 posts since Dec 2006
Reputation Points: 827
Solved Threads: 780
Skill Endorsements: 9
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
pyTony
pyMod
6,312 posts since Apr 2010
Reputation Points: 879
Solved Threads: 987
Skill Endorsements: 26
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.
vegaseat
DaniWeb's Hypocrite
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 37
Question Answered as of 2 Years Ago by
vegaseat,
woooee,
predator78
and 1 other