Tuples

A tuple is similar to a [list](/tutorials/list), but it is immutable, which means its values cannot be changed once it is created. Think of a tuple as a collection of items that are ordered and unchangeable.

To create a tuple, you use parentheses `()` and separate the items with commas. Here's an example:

coordinates = (3, 4)
In this example, we created a tuple called `coordinates` that contains two items: `3` and `4`. The order of the items in the tuple is preserved.

You can access individual items in a tuple by their index, just like with lists. The index starts from `0` for the first item, `1` for the second item, and so on. For example:

print(coordinates[0])  # Output: 3
print(coordinates[1])  # Output: 4
3
4
In this code, we use square brackets after the tuple name to access specific items. `coordinates[0]` gives us the first item in the tuple, which is `3`, and `coordinates[1]` gives us the second item, which is `4`.

However, unlike lists, you cannot change the value of an item in a tuple once it is created. If you try to assign a new value to an index in a tuple, you will get an error. For example:

coordinates[0] = 5  # This will give an error
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 coordinates[0] = 5  # This will give an error

TypeError: 'tuple' object does not support item assignment
Tuples are commonly used when you want to group related values together, especially when those values should not be modified. For example, you might use a tuple to represent the coordinates of a point in a 2D plane, where the x-coordinate and y-coordinate are fixed.

You can also use tuples to assign multiple variables at once. This is called tuple unpacking. Here's an example:

point = (3, 4)
x, y = point
print(x)  # Output: 3
print(y)  # Output: 4
3
4
In this code, we assign the values of the tuple `point` to the variables `x` and `y` using tuple unpacking. Now, `x` will have the value `3` and `y` will have the value `4`.