Tuples use parentheses ()
or comma-separated values to store data.
my_tuple = ("apple", "banana", "cherry")
single_item = ("apple",) # Note the trailing comma!
empty_tuple = ()
mixed_tuple = (1, "text", True)
my_tuple = ("Python", 3.10, False)
print(my_tuple[0]) # Output: 'Python'
print(my_tuple[-1]) # Output: False
print(my_tuple[1:]) # Output: (3.10, False)
Method | Description |
---|---|
count(x) | Returns number of occurrences of x |
index(x) | Returns the first index of value x |
t = (1, 2, 2, 4)
print(t.count(2)) # Output: 2
print(t.index(4)) # Output: 3
def user_info():
return ("Alice", 30)
name, age = user_info()
print(name) # Alice
print(age) # 30
Tuples can contain lists, other tuples, or even objects:
nested = ((1, 2), [3, 4], "hello")
print(nested[0][1]) # Output: 2
print(nested[1][0]) # Output: 3
Tuples are powerful, lightweight containers for ordered and fixed data. Their immutability adds safety to programs, and their compatibility with functional and object-oriented patterns makes them a key tool in Python’s design philosophy.