Tuples
A tuple is similar to a list in that it is an ordered sequence of elements. However, the key difference is that tuples are immutable—once created, their contents cannot be changed (added, removed, or modified).
Tuples are defined using parentheses (), though parentheses are often optional.
Creating Tuples
python
Standard tuple
coordinates = (10.0, 20.5)
Tuple without parentheses (Python interprets this as a tuple)
color = 'red', 'green', 'blue'
Single-item tuple (requires trailing comma!)
single_item = (5,) print(type(single_item)) # <class 'tuple'>
Without the comma, it's just an integer expression:
not_a_tuple = (5) print(type(not_a_tuple)) # <class 'int'>
Accessing and Slicing
Accessing elements and slicing works exactly like lists and strings.
python rgb = ('red', 'green', 'blue') print(rgb[1]) # Output: green print(rgb[0:2]) # Output: ('red', 'green')
Immutability Example
python point = (1, 2, 3)
point[0] = 5 # TypeError: 'tuple' object does not support item assignment
Why use Tuples?
- Safety: If data should not change (like coordinates or database records), tuples prevent accidental modification.
- Performance: Tuples are slightly faster than lists.
- Dictionary Keys: Tuples can be used as dictionary keys (which lists cannot, because keys must be immutable).