It is a collection of homogenous and heterogeneous elements.
Tuples can be created by placing a comma-separated sequence of elements within parentheses.
Examples:
# Empty tuple
empty_tuple = ()
# Tuple of integers
int_tuple = (1, 2, 3, 4, 5)
# Tuple of strings
string_tuple = ("apple", "banana", "cherry")
# Tuple of mixed data types
mixed_tuple = (1, "apple", 3.14, True)
# Tuple without parentheses (tuple packing)
packed_tuple = 1, "apple", 3.14, True
# Single element tuple (note the comma)
single_element_tuple = (5,)
Elements in a tuple are accessed using indexing, with the first element at index 0. Negative indexing is also supported, with -1 being the last element.
Examples:
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry
You can extract a portion of a tuple using slicing, which creates a new tuple containing the desired elements.
Examples:
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(numbers[2:5]) # Output: (2, 3, 4)
print(numbers[:3]) # Output: (0, 1, 2)
print(numbers[5:]) # Output: (5, 6, 7, 8, 9)
print(numbers[-3:]) # Output: (7, 8, 9)
print(numbers[::2]) # Output: (0, 2, 4, 6, 8) (step slicing)
You can concatenate tuples using the + operator and repeat tuples using the * operator.
Examples:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Concatenation
concat_tuple = tuple1 + tuple2
print(concat_tuple) # Output: (1, 2, 3, 4, 5, 6)
# Repetition
repeated_tuple = tuple1 * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Tuples support only two built-in methods: count() and index().
Examples:
numbers = (1, 2, 3, 2, 4, 2, 5)
# Count the occurrences of an element
count_of_twos = numbers.count(2)
print(count_of_twos) # Output: 3
# Find the index of the first occurrence of an element
index_of_four = numbers.index(4)
print(index_of_four) # Output: 4
Tuple unpacking allows you to assign each element of a tuple to a variable.
Examples:
# Basic unpacking
point = (10, 20)
x, y = point
print(x) # Output: 10
print(y) # Output: 20
# Unpacking with mixed types
person = ("Alice", 30, "Engineer")
name, age, profession = person
print(name) # Output: Alice
print(age) # Output: 30
print(profession) # Output: Engineer
# Using * to unpack remaining elements
numbers = (1, 2, 3, 4, 5)
a, b, *rest = numbers
print(a) # Output: 1
print(b) # Output: 2
print(rest) # Output: [3, 4, 5]
Tuples can contain other tuples (or any other data type) as elements, creating nested structures.
Examples:
nested_tuple = ((1, 2), (3, 4), (5, 6))
print(nested_tuple[0]) # Output: (1, 2)
print(nested_tuple[1][1]) # Output: 4