Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Tuples Introduction To Tuples

Jing Zhang
PLUS
Jing Zhang
Courses Plus Student 6,465 Points

Why I can change the element in a tuple??!!

my_third_tuple = ([1,2,3])
print(my_third_tuple)
>>> [1, 2, 3]

my_third_tuple[1] = 5
my_third_tuple
>>> [1, 5, 3]

what?!! I was expecting an error! I am using Jupyter Notebook py35

fixed code formatting

3 Answers

You could have created a 1 element tuple by adding a comma after the list.

However, if your tuple contains a list, you will still be able to change that list. What you can't do is change the reference to that list to be something else.

>>> my_tuple = ([1, 2, 3],)
>>> my_tuple
([1, 2, 3],)
>>> type(my_tuple)
<class 'tuple'>
>>> my_tuple[0][1] = 5
>>> my_tuple
([1, 5, 3],)
>>> my_tuple[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
Seth Kroger
Seth Kroger
56,413 Points

([1, 2, 3]) is an array. One way to look at is because it's only a single value, the "tuple" is collapsed to the value. If it was (1, 2, 3) it would be a 3-element tuple and it wouldn't change.

Jing Zhang
PLUS
Jing Zhang
Courses Plus Student 6,465 Points

Thank you! I am too careless. I created the tuple wrong. What I created are lists, instead of tuples.