Python tuples are immutable, ordered sequences of elements. Unlike lists, once a tuple is created, it cannot be modified. Tuples are useful for fixed collections of items and are often used to store heterogeneous data.
A tuple in Python is created by placing all the elements (items) inside parentheses ()
, separated by commas.
my_tuple = (1, 2, 3)
mixed_tuple = (1, "hello", 3.14)
Tuples can contain elements of different types, including other tuples (nested tuples).
Indexing: Access elements by their index. Python uses zero-based indexing.
my_tuple = (1, 2, 3)
first_item = my_tuple[0] # 1
last_item = my_tuple[-1] # 3
Slicing: Access a range of elements using slicing.
my_tuple = (1, 2, 3, 4, 5)
sub_tuple = my_tuple[1:4] # (2, 3, 4)
Tuple unpacking allows you to assign elements of a tuple to multiple variables in a single statement.
my_tuple = (1, 2, 3)
a, b, c = my_tuple # a = 1, b = 2, c = 3
You can use the *
operator to capture excess elements.
my_tuple = (1, 2, 3, 4, 5)
a, *b, c = my_tuple # a = 1, b = [2, 3, 4], c = 5
Concatenation: Combine two or more tuples using the +
operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
result = tuple1 + tuple2 # (1, 2, 3, 4, 5)
Repetition: Repeat a tuple using the *
operator.
my_tuple = (1, 2)
result = my_tuple * 3 # (1, 2, 1, 2, 1, 2)
my_tuple = (1, 2, 3)
exists = 2 in my_tuple # True
count(item)
: Return the number of occurrences of an item in the tuple.
my_tuple = (1, 2, 2, 3)
my_tuple.count(2) # 2
index(item, start=0, end=len(tuple))
: Return the index of the first occurrence of an item.
my_tuple = (1, 2, 3)
my_tuple.index(2) # 1
Accidental Modification: Tuples themselves are immutable, but if they contain mutable elements (e.g., lists), those elements can still be modified.
my_tuple = (1, 2, [3, 4])
my_tuple[2].append(5) # my_tuple becomes (1, 2, [3, 4, 5])
Confusing Tuples with Single Elements: A tuple with a single element must include a trailing comma; otherwise, it is not recognized as a tuple.
single_element_tuple = (1,) # This is a tuple
not_a_tuple = (1) # This is an integer
Use of Tuples as Keys in Dictionaries: Be cautious when using tuples containing mutable elements as dictionary keys, as this can lead to unexpected behavior.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y) # 1 2
dataclasses
introduced in Python 3.7.This comprehensive guide should help you understand Python tuples, their features, and best practices for using them effectively in your programs.