Kahibaro
Discord Login Register

Tuples

What is a Tuple?

A tuple is an ordered collection of items, similar to a list, but cannot be changed after it is created.

Tuples are written using parentheses () instead of square brackets [].

numbers = (10, 20, 30)
person = ("Alice", 30, True)

Creating Tuples

Basic tuples

You create a tuple by putting values inside parentheses, separated by commas:

empty_tuple = ()
colors = ("red", "green", "blue")
mixed = ("Alice", 25, 1.75, True)

Tuple without parentheses

Python lets you omit the parentheses in many cases. The commas are what really make a tuple:

coords = 10, 20
print(coords)        # (10, 20)
print(type(coords))  # <class 'tuple'>

Still, using parentheses is clearer and recommended for beginners.

One‑item (single-element) tuples

A common beginner trap: a single value in parentheses is not a tuple:

not_a_tuple = (5)
print(type(not_a_tuple))   # <class 'int'>

To make a one‑item tuple, you must add a trailing comma:

one_item = (5,)
print(type(one_item))  # <class 'tuple'>
another_one = "hello",
print(type(another_one))  # <class 'tuple'>

Accessing Tuple Items

Tuples use zero-based indexing, just like strings and lists.

point = (3, 4, 5)
print(point[0])  # 3
print(point[1])  # 4
print(point[2])  # 5

You can also use negative indexes:

colors = ("red", "green", "blue")
print(colors[-1])  # "blue"
print(colors[-2])  # "green"

Slicing tuples

You can get a slice (part) of a tuple using start:stop:

data = (10, 20, 30, 40, 50)
print(data[1:4])   # (20, 30, 40)
print(data[:3])    # (10, 20, 30)
print(data[2:])    # (30, 40, 50)

Slicing a tuple returns a new tuple.

Tuple Immutability

Tuples are immutable: after you create one, you cannot change its contents.

This means you cannot:

nums = (1, 2, 3)
# All of these cause errors:
# nums[0] = 10       # TypeError
# nums.append(4)     # AttributeError
# del nums[1]        # TypeError

If you want to "change" a tuple, you actually create a new tuple.

nums = (1, 2, 3)
new_nums = (0,) + nums + (4,)
print(new_nums)  # (0, 1, 2, 3, 4)

Or convert to a list, change it, then convert back:

nums = (1, 2, 3)
temp_list = list(nums)  # convert to list
temp_list.append(4)
nums = tuple(temp_list)  # convert back to tuple
print(nums)  # (1, 2, 3, 4)

When to Use Tuples Instead of Lists

Use a tuple when:

Examples:

# Coordinates (x, y)
position = (100, 200)
# RGB color (red, green, blue)
color = (255, 128, 0)
# Birth date (year, month, day)
birth_date = (1990, 5, 23)

Tuples are often used for fixed structures where each position has a meaning.

Tuple Operations

Tuples support many of the same operations as strings and lists (except mutation).

Length

Use len() to count the items:

values = (10, 20, 30, 40)
print(len(values))  # 4

Membership: `in` and `not in`

Check if a value is in a tuple:

nums = (1, 2, 3, 4)
print(3 in nums)      # True
print(5 in nums)      # False
print(5 not in nums)  # True

Concatenation and repetition

You can join tuples with + and repeat them with *:

a = (1, 2)
b = (3, 4)
c = a + b
print(c)  # (1, 2, 3, 4)
d = a * 3
print(d)  # (1, 2, 1, 2, 1, 2)

These operations create new tuples, because the original ones cannot be changed.

Tuple Methods

Tuples have a very small set of methods (because they are immutable).

The two common ones:

nums = (1, 2, 2, 3, 2)
print(nums.count(2))   # 3
print(nums.index(3))   # 3

If index() doesn’t find the value, it raises a ValueError.

nums = (1, 2, 3)
# nums.index(5)  # ValueError: tuple.index(x): x not in tuple

Tuple Packing and Unpacking

Packing

Packing means putting multiple values into a tuple in a single assignment:

person = "Alice", 25, "Paris"   # packed into a tuple
print(person)                   # ('Alice', 25, 'Paris')

Unpacking

Unpacking means assigning elements of a tuple to multiple variables at once.

person = ("Alice", 25, "Paris")
name, age, city = person
print(name)  # Alice
print(age)   # 25
print(city)  # Paris

The number of variables must match the number of tuple items:

data = (1, 2, 3)
# a, b = data       # ValueError: not enough values to unpack
# a, b, c, d = data # ValueError: too many values to unpack

Using `_` to ignore values

You can use _ as a throwaway variable for values you don't care about:

record = ("Bob", 30, "Engineer")
name, _, job = record
print(name)  # Bob
print(job)   # Engineer

This doesn’t change how Python works; _ is just a normal variable name by convention.

Unpacking with `*` (star)

You can use * to collect "the rest" of the values into a list:

numbers = (10, 20, 30, 40, 50)
first, *middle, last = numbers
print(first)   # 10
print(middle)  # [20, 30, 40]
print(last)    # 50

Tuples as Dictionary Keys (Preview)

Because tuples are immutable, they can be used as keys in dictionaries (unlike lists).

Example (you will see dictionaries in another chapter, but this is useful to know):

# a tuple representing a point (x, y)
point = (10, 20)
locations = {
    point: "Tree",
}
print(locations[(10, 20)])  # "Tree"

Lists cannot be used as keys, but tuples can, which is one practical reason tuples exist.

Nested Tuples

Tuples can contain other tuples (and other collections):

grid = (
    (1, 2, 3),
    (4, 5, 6),
    (7, 8, 9),
)
print(grid[0])     # (1, 2, 3)
print(grid[1][2])  # 6

This is useful to represent 2D data (like a grid or matrix) that should not change.

Common Tuple Mistakes for Beginners

1. Forgetting the comma in single-element tuples

value = (5)    # just 5, not a tuple
print(type(value))  # <class 'int'>
value = (5,)   # now it's a tuple
print(type(value))  # <class 'tuple'>

2. Trying to modify a tuple item

data = (1, 2, 3)
# data[0] = 10  # TypeError

If you need to change it, convert to a list, or use a list instead of a tuple from the start.

3. Mismatch when unpacking

coords = (10, 20, 30)
# x, y = coords      # ValueError: not enough values to unpack
# x, y, z, w = coords  # ValueError: too many values to unpack

Always ensure the number of variables matches the number of tuple items (unless you use * to collect extras).

Practice Ideas

Try writing small snippets that:

  1. Create a tuple describing yourself: (name, age, country), then unpack it into variables.
  2. Create a tuple of 5 numbers and:
    • Print the first and last.
    • Print the length.
    • Check whether a certain number is in the tuple.
  3. Make a "coordinate" tuple (x, y), then use it as a key in a small dictionary (after reading the dictionaries chapter).
  4. Experiment with converting between lists and tuples using list() and tuple().

Views: 16

Comments

Please login to add a comment.

Don't have an account? Register now!