Introduction to Tuples in Python
In this lesson, you will learn about tuples. You will understand their differences from lists, and explore typical use cases.
Let's create our first tuple:
Looks almost like a list don't you think?
So, besides the parentheses and square brackets, what's the difference?
Tuples are immutable, meaning their elements cannot be changed after creation. Lists, on the other hand, are mutable.
Let's see what happens if we try to update a tuple like we did with a list:
Other than that, tauples are pretty similar to lists.
You can access tuple elements using indices and slicing:
You can get the index of an element:
You can get the length of a tuple:
There's more you can do with tuples, which will be covered in future chapters.
But, why should you use tuples?
First of all, the immutability of tuples can be advantageous.
If you have a collection of constant elements that never change, it's better to use a tuple to store them. This way, you cannot accidently change the values.
Using tuples for constant values also improves the readability of your code. When you encounter a tuple, you can be certain that its values remain unchanged.
Most importantly, tuples improve the performance of your code. Due to their immutability, they use less memory and accessing tuple elements is generally faster than accessing list elements.
That's why, whenever you have a collection of constant elements, store them in a tuple instead of a list.