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.).
Creating a tuple
Section titled “Creating a tuple”Let’s make a tuple of fruits.
# List of fruitsfruits = ('apple', 'banana', 'orange', 'pear', 'grape', 'mango')print(fruits)
# To create a tuple with a single element, add a comma at the endsingle_tuple = (1,)print(single_tuple)
Output:
('apple', 'banana', 'orange', 'pear', 'grape', 'mango')(1,)
Indexing
Section titled “Indexing”To access a particular element of the tuple, indexing is carried out as follows:
# List of fruitsfruits = ('apple', 'banana', 'orange', 'pear', 'grape', 'mango')print(fruits[1])
Output:
banana
Slicing
Section titled “Slicing”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.
# List of fruitsfruits = ('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:
('banana', 'orange', 'pear')('apple', 'banana', 'orange')('orange', 'pear', 'grape', 'mango')('apple', 'orange', 'grape')('mango', 'grape', 'pear', 'orange', 'banana', 'apple')
When to use tuples?
Section titled “When to use tuples?”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.
# Tuple as a dictionary keyd = {('x','y'): 42}print(d[('x','y')])