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