DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Tuples Explained Simply (Immutable Sequences)

Tuples are ordered collections similar to lists, but they cannot be changed after creation. This makes them useful for data that should stay fixed.

What is a tuple?

A tuple is created with parentheses () and items separated by commas.

coordinates = (10, 20)
colors = ("red", "green", "blue")
single_item = (5,)  # Note the comma for one item
Enter fullscreen mode Exit fullscreen mode

You can also create a tuple without parentheses:

point = 3, 4
Enter fullscreen mode Exit fullscreen mode

An empty tuple:

empty_tuple = ()
Enter fullscreen mode Exit fullscreen mode

Tuples can contain mixed types and are immutable.

Accessing elements

Use indexes just like lists (starting at 0).

colors = ("red", "green", "blue")

print(colors[0])   # red
print(colors[-1])  # blue
Enter fullscreen mode Exit fullscreen mode

Slicing works too:

print(colors[1:3])  # ("green", "blue")
Enter fullscreen mode Exit fullscreen mode

Why use tuples instead of lists?

  • Tuples are immutable: you cannot add, remove, or change items.
  • This protects data from accidental changes.
  • Tuples are faster than lists.
  • Tuples can be used as dictionary keys (lists cannot).

Attempting to modify raises an error:

colors[0] = "yellow"  # TypeError: 'tuple' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

Common operations

Get length:

print(len(colors))  # 3
Enter fullscreen mode Exit fullscreen mode

Check membership:

print("green" in colors)  # True
Enter fullscreen mode Exit fullscreen mode

Loop over a tuple:

for color in colors:
    print(color)
Enter fullscreen mode Exit fullscreen mode

Packing and unpacking

Tuples make it easy to assign multiple values.

Packing:

person = ("Alex", 25, "Berlin")
Enter fullscreen mode Exit fullscreen mode

Unpacking:

name, age, city = person
print(name)  # Alex
print(age)   # 25
Enter fullscreen mode Exit fullscreen mode

This works with functions too:

def get_point():
    return (10, 20)

x, y = get_point()
print(x, y)  # 10 20
Enter fullscreen mode Exit fullscreen mode

Simple examples

Store fixed settings:

screen_size = (1920, 1080)  # Cannot be changed accidentally
Enter fullscreen mode Exit fullscreen mode

RGB color values:

red = (255, 0, 0)
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Create tuples with parentheses (and a comma for single items).
  • Access elements with indexes and slicing.
  • Tuples are immutable and faster than lists.
  • Use unpacking to assign multiple values easily.
  • Choose tuples for data that should not change.

Practice using tuples for fixed collections. They are a safe and efficient alternative to lists in Python programs.

Top comments (0)