beginnerData Structures
Tuples
Immutable ordered sequences for fixed collections.
In this lesson
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 element45print(point[0]) # 36print(len(colors)) # 37print(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 = coordinates34print(x, y, z)56# Swap variables elegantly7a, b = 1, 28a, b = b, a9print(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", 3034name, age = get_name_and_age()5print(f"{name} is {age} years old")
Output
Alice is 30 years old