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])
5
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by vegaseat
Featured Replies
  • 1

    [QUOTE=;][/QUOTE] 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 [code]my_tuple = (1, 2, 3, [4, 5, 6]) new_list = [4, 5, 6] my_tuple[3] = new_list ## new memory address … Read More

  • 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. Read More

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"

Edited by woooee: n/a

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

Edited by pyTony: n/a

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.