A tuple is an immutable sequence type in Python. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation. Tuples are defined by enclosing elements in parentheses ()
.
example_tuple = (1, 2, 3, 'apple', 'banana', 3.14) print(example_tuple)
Output:
(1, 2, 3, 'apple', 'banana', 3.14)
example_tuple = (1, 2, 3, 'apple', 'banana', 3.14) print(example_tuple[0]) # Accessing the first element print(example_tuple[-1]) # Accessing the last elements
Output:
1 3.14
Returns the length (number of elements) in a tuple.
example_tuple = (1, 2, 3, 'apple', 'banana', 3.14)
print(len(example_tuple))
Output:
6
Returns the largest element in a tuple.
num_tuple = (1, 2, 3, 10, 5)
print(max(num_tuple))
Output:
10
Returns the smallest element in a tuple.
num_tuple = (1, 2, 3, 10, 5)
print(min(num_tuple))
Output:
1
Returns the sum of all elements in a tuple.
num_tuple = (1, 2, 3, 10, 5)
print(sum(num_tuple))
Output:
21
Returns the number of times a specified element appears in a tuple.
example_tuple = (1, 2, 3, 'apple', 'banana', 3.14, 1, 2, 1)
print(example_tuple.count(1))
Output:
3
Returns the index of the first occurrence of a specified element in a tuple.
example_tuple = (1, 2, 3, 'apple', 'banana', 3.14)
print(example_tuple.index('banana'))
Output:
4
Tuples can be created by packing multiple values into a single variable. Unpacking is the process of assigning the values of a tuple to individual variables.
# Tuple packing
packed_tuple = 1, 2, 3, 'apple', 'banana'
# Tuple unpacking
a, b, c, d, e = packed_tuple
print(packed_tuple)
print(a, b, c, d, e)
Output:
(1, 2, 3, 'apple', 'banana')
1 2 3 apple banana
example_tuple = (1, 2, 3, 'apple', 'banana', 3.14)
example_list = list(example_tuple)
example_list[0] = 'modified' # Modify the list
example_tuple = tuple(example_list)
print(example_tuple)
Output:
('modified', 2, 3, 'apple', 'banana', 3.14)
tuple1 = (1, 2, 3)
tuple2 = ('apple', 'banana')
modified_tuple = tuple1 + tuple2
print(modified_tuple)
Output:
(1, 2, 3, 'apple', 'banana')
example_tuple = (1, 2, 3, 'apple', 'banana', 3.14)
modified_tuple = example_tuple[:3] + ('orange',) + example_tuple[4:]
print(modified_tuple)
Output:
(1, 2, 3, 'orange', 'banana', 3.14)