Creating Tuples
Tuples are similar to lists but immutable. Once created, their contents cannot be changed. This makes them ideal for fixed collections of data, like coordinates.
point = (3, 5)
print(point)
Accessing Elements
Tuples use indexing just like lists. You can retrieve elements by position, making them easy to work with.
print(point[0], point[1])
Immutability
The key feature of tuples is immutability. This ensures data remains constant, which is useful for values that should never change, like configuration settings.
# point[0] = 4 # ❌ Error
Single‑Item Tuples
To create a tuple with one item, you must include a trailing comma. Without it, Python interprets the value as just a number in parentheses.
single = (7,)
print(single)
Unpacking Tuples
Tuples can be unpacked into separate variables, allowing you to assign multiple values at once. This is a neat way to handle grouped data.
x, y = point
print(x, y)
My take
Tuples are reliable containers for fixed data. Their immutability ensures values remain constant, making them useful for coordinates, configurations, and grouped values.
Top comments (0)