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 Sequences Sequence Operations Concatenation and Multiplication

rosieg
rosieg
1,666 Points

Concatenating a tuple

My understanding is that tuples cannot be modified, ie if you add two tuples together the result has to be assigned to a new tuple. However, when I run the following code in the workspace:

tup1 = (1, 2, 3, 4, 5)
tup2 = (6, 7, 8, 9, 10)

tup1 = tup1 + tup2
print(tup1)

It works fine and returns (1, 2, 3, 4, 5, 6, 7, 9, 10). I expected it to fail as I am modifying tup1?

2 Answers

Steven Parker
Steven Parker
231,268 Points

What happens here is that the variable that originally contained the first tuple (tup1) is being reassigned with a newly created tuple built from both of the originals.

The original first tuple isn't modified, it is disposed.

If you want to see what happens when you attempt to modify a tuple, you could try something like this:

tup1[2] = 99
rosieg
rosieg
1,666 Points

Got you I think. The tuple isn't changed, the variable (tup1) is? And I have effectively just lost the original tup1 - something I will need to be careful of in the future!