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)

Output:

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

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 (or segmentation) 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]) # ('apple', 'orange', 'grape')
print(fruits[::-1]) # ('mango', 'grape', 'pear', 'orange', 'banana', 'apple')

Output:

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