beginnerData Structures

Tuples

Immutable ordered sequences for fixed collections.

01Creating Tuples

Tuples are immutable sequences defined with parentheses. Once created, elements cannot be changed.

Python
1point = (3, 4)
2colors = ("red", "green", "blue")
3single = (42,) # comma needed for single element
4
5print(point[0]) # 3
6print(len(colors)) # 3
7print(type(single)) # <class 'tuple'>
Output
3
3
<class 'tuple'>

02Tuple Unpacking

Assign tuple elements to multiple variables at once.

Python
1coordinates = (10, 20, 30)
2x, y, z = coordinates
3
4print(x, y, z)
5
6# Swap variables elegantly
7a, b = 1, 2
8a, b = b, a
9print(a, b)
Output
10 20 30
2 1

03When to Use Tuples

Use tuples for data that should not change: coordinates, RGB colors, database records, dictionary keys, and function returns of multiple values.

Python
1def get_name_and_age():
2 return "Alice", 30
3
4name, age = get_name_and_age()
5print(f"{name} is {age} years old")
Output
Alice is 30 years old