Skip to content

Tuples

In Python, a tuple is an ordered and immutable collection of elements. Tuples are represented between parentheses and separated by commas. They are useful for storing data that should not change after creation.

Tuples are:

  • Immutable: Once a tuple is created, you cannot add, remove, or modify elements.

  • Ordered: Elements in a tuple have a specific order, and they can be accessed through their index.

  • Heterogeneous: Tuples can contain elements of different data types (integers, strings, booleans, etc.).

Let’s make a tuple of fruits.

tuple.py
# List of fruits
fruits = ('apple', 'banana', 'orange', 'pear', 'grape', 'mango')
print(fruits)
# To create a tuple with a single element, add a comma at the end
single_tuple = (1,)
print(single_tuple)

Output:

terminal
('apple', 'banana', 'orange', 'pear', 'grape', 'mango')
(1,)

To access a particular element of the tuple, indexing is carried out as follows:

tuple.py
# List of fruits
fruits = ('apple', 'banana', 'orange', 'pear', 'grape', 'mango')
print(fruits[1])

Output:

terminal
banana

In Python, slicing in a tuple is a technique to obtain a sub-tuple by extracting a range of elements, without modifying the original tuple.

tuple[start:end:step]
  • start: index from where to begin (included).
  • end: index where to finish (not included).
  • step: (optional) interval between elements.
tuple.py
# List of fruits
fruits = ('apple', 'banana', 'orange', 'pear', 'grape', 'mango')
print(fruits[1:4]) # ('banana', 'orange', 'pear')
print(fruits[:3]) # ('apple', 'banana', 'orange')
print(fruits[2:]) # ('orange', 'pear', 'grape', 'mango')
print(fruits[::2]) # ('apple', 'orange', 'grape')
print(fruits[::-1]) # ('mango', 'grape', 'pear', 'orange', 'banana', 'apple')

Output:

terminal
('banana', 'orange', 'pear')
('apple', 'banana', 'orange')
('orange', 'pear', 'grape', 'mango')
('apple', 'orange', 'grape')
('mango', 'grape', 'pear', 'orange', 'banana', 'apple')

Tuples are useful when you want to represent data that should not change. Main advantages:

  • Immutability: prevents accidental modifications (for example, configuration or coordinates).
  • Efficiency: usually a bit faster and use less memory than lists.
  • Hashable: can be used as keys in dictionaries if all their elements are immutable.
example.py
# Tuple as a dictionary key
d = {('x','y'): 42}
print(d[('x','y')])