Python Tuples

What Is a Tuple?

A tuple is a collection of items, just like a list, but it cannot be changed after it's created. Tuples are written using round brackets ().

Example:

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

Here, we created a tuple called fruits that holds three items. The round brackets mean it's a tuple.

Why Use Tuples?

  • You want to keep your data safe and unchangeable.
  • You want to group related values together, like a pair of coordinates: (x, y).
  • Tuples are faster than lists and take less memory.

1. Create Tuple

This example shows how to create a tuple in Python using parentheses (). Here, fruits is a tuple containing three string elements.

Note: Even a single-element tuple must have a trailing comma, like single = ("apple",) to be recognized as a tuple.

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

2. Read Items in Tuple

Tuples in Python store items in an ordered way, meaning each item has a specific index starting from 0. To access an item, use square brackets with the index.

For example, fruits[0] retrieves the first item in the tuple, which is "apple".

Indexing allows direct access to any element: fruits[1] gives "banana", and fruits[2] gives "cherry".

  fruits = ("apple", "banana", "cherry")
print(fruits[0])
print(fruits[1])
apple
banana

3. Check Length of Tuple

Use the built-in len() function to find the number of elements in the tuple fruits.

The syntax len(tuple_name) returns an integer indicating how many items are stored inside the tuple.

In this case, the tuple has 3 items, so len(fruits) returns 3.

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

This tells us the tuple has 3 items.

4. Loop Through a Tuple

Tuples, like lists, are iterable in Python. We can use a for loop to iterate over the items in a tuple.

  fruits = ("apple", "banana", "cherry")
for fruit in fruits:
    print(fruit)
apple
banana
cherry
apple
banana
cherry

5. Check If Item Exists

The expression "banana" in fruits checks whether the string "banana" is present in the tuple fruits. The in keyword returns a boolean: True if the item exists, otherwise False.

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

Things You Cannot Do With Tuples

Because tuples are unchangeable:

  • You can't add items
  • You can't remove items
  • You can't change any item

Trying to Change a Tuple (will cause an error)

fruits[0] = "orange"
TypeError: 'tuple' object does not support item assignment

Python will give you an error if you try to change the content.