Understand Immutability with Python Tuples

Ceora Ford
InstructorCeora Ford
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

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.

egghead
egghead
~ just now

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today