DEV Community

Cover image for Tuples in Python: Immutable Data Made Simple
Mary Nyandia
Mary Nyandia

Posted on

Tuples in Python: Immutable Data Made Simple

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)

Enter fullscreen mode Exit fullscreen mode

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])

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)