Tuple Syntax#
Note
Source: Python-specific — C# has no direct equivalent in this edition. Python tuples are the immutable counterpart to lists. Use them when a fixed-size, ordered collection should not be modified after creation.
A tuple is an ordered, immutable sequence of values. Once created, its elements cannot be changed.
Creating Tuples#
Write a tuple with parentheses and commas:
point = (3, 7)
rgb = (255, 128, 0)
empty = ()
Parentheses are optional in most contexts — the comma is what makes a tuple:
point = 3, 7 # also a tuple
print(type(point))
Output:
<class 'tuple'>
A single-element tuple requires a trailing comma; without it, Python treats the parentheses as grouping:
one = (42,) # tuple with one element
not_one = (42) # just the integer 42
print(type(one), type(not_one))
Output:
<class 'tuple'> <class 'int'>
Indexing and Length#
Tuples support indexing, slicing, and len() exactly like lists:
rgb = (255, 128, 0)
print(rgb[0]) # 255
print(rgb[-1]) # 0
print(len(rgb)) # 3
Immutability#
Attempting to change an element raises a TypeError:
rgb = (255, 128, 0)
rgb[0] = 100 # TypeError: 'tuple' object does not support item assignment
Tuples vs. Lists#
Tuple |
List |
|---|---|
Immutable |
Mutable |
|
|
Can be a dict key |
Cannot be a dict key |
Slightly faster |
More flexible |
Use a tuple when the structure is fixed by design: a coordinate, an RGB colour, a database record field.
Use a list when items will be added, removed, or reordered.
Converting Between Tuples and Lists#
t = (1, 2, 3)
lst = list(t) # convert tuple → list
lst.append(4)
t2 = tuple(lst) # convert list → tuple
print(t2)
Output:
(1, 2, 3, 4)