Understand Immutability with Python Tuples

Ceora Ford
InstructorCeora Ford
Share this video with your friends

Social Share Links

Send Tweet

Tuples are immutable so there is no way to add or replace items in tuples. There is a way to get around this by adding two tuples into one.

Ceora Ford: [0:01] Working from my_tuple, we're going to try to add another item to the end of this tuple. We'll do this by using the append() method. I'm going to append a list of my favorite foods which includes pizza, lasagna, and cookies.

[0:30] As you can see, we get an error. This is because tuples are immutable which means that after they've been created, we cannot change or alter them. There is a way to get around this though if you really want to add a new item into your tuple.

[0:44] You can do this by adding two tuples together into one. We'll create a variable called my_tuple2 and we'll combine the original my_tuple with a one-item tuple that contains the list of my favorite foods. We'll remember also to add the ending comma since this is a one-item tuple.

[1:09] Now when we type my_tuple2 into the [inaudible] , you can see it returns back to us a combination of the original my_tuple and the list of my favorite foods.