Summer Deals - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Tuple basics
6. Tuples are immutable
Tuples in functions
Summary

Instruction

Good! You may be wondering what the difference is between tuples and lists. After all, they are so similar!

The main difference is that tuples are immutable, which means once you create a tuple, you can't change it. There is no way to delete an element from a tuple or to add a new one.

user_data = ('John', 'Smith', 29, 1.85, 'British')
user_data[5] = 'male' # won't work!
del user_data[2]      # won't work!

On the second line, we want to add a new element at index 4, but this will throw an error. Similarly, on the third line, we can't delete that item.

Immutability has a number of advantages:

  • Immutable objects are a bit more lightweight and work faster.
  • Only immutable objects can be used as keys in a dictionary.
  • Immutability guarantees that once you create an object, it remains the same.

Exercise

Try to add a new element to the train_connection tuple. See what kind of error is shown. Then, try to delete an element from the tuple. Again, observe the error.

Once you're done, click I'm done. Next exercise to continue.