Tuples

Tuple is a collection of items of any type. It is immutable, which means that once created, it cannot be modified. Otherwise, it is very similar to a list.

As usual, let's start with a simple example:

fruits = ("apple", "banana", "cherry")
print(fruits)

which produces the following output:

('apple', 'banana', 'cherry')

You can access tuple items by index, just like with lists:

print(fruits[0])
print(fruits[1])
print(fruits[2])

which gives:

apple
banana
cherry

As with lists, you can use negative indices to access items from the end of the tuple:

print(fruits[-1])

which prints:

cherry

But unlike lists, tuples are immutable, which means that you cannot modify them. For instance, if you try to assign a new value to an item:

fruits[0] = "pear"

you will get an error:

Traceback (most recent call last):
  File "tuples.py", line 17, in <module>
    fruits[0] = "pear"
    ~~~~~~^^^
TypeError: 'tuple' object does not support item assignment

Tuple methods

To check if an item is in a tuple, you can use the in operator:

numbers = (1, 2, 3, 1)

print(1 in numbers)
print(4 not in numbers)

which produces:

True
True

Note also that in the example above, we have the value 1 twice in the tuple. Tuples, as lists, can contain duplicate items.

To obtain size of a tuple, you can use the len() function:

print(len(numbers))
# => 4

Tuple type

To see type of the tuple, you can use the type() function, as usual:

print(type(numbers))
# => <class 'tuple'>

One interesting case of a tuple is a tuple with a single item. In this case, you need to add a comma after the item, otherwise Python will treat it as a regular value in parentheses:

single_value = (1)
print(type(single_value))

a_tuple = (1,)
print(type(a_tuple))

which prints:

<class 'int'>
<class 'tuple'>

When to use tuples over lists

Prefer tuples over lists when you want to make sure that the collection is not modified. Tuples are generally faster and more memory efficient than lists.