Learn Python: The Fundamentals

Tuples in Python are a lot like lists — they can hold multiple values and are ordered — but there’s one major difference: tuples can’t be changed. Once you create a tuple, that’s it. You can’t add, remove, or modify its contents. This makes tuples perfect when you want to store a group of values that should stay the same throughout your program.

 

Creating Tuples

To create a tuple, wrap your values in parentheses () and separate them with commas. You can store all sorts of data types — strings, numbers, even other tuples. Just remember: if you’re creating a tuple with only one item, you need to include a comma after it. Otherwise, Python won’t recognize it as a tuple.

 

coordinates = (10, 20)
person = ("Alice", 25, "Engineer")
single = (5,)   # Single-item tuple

 

Accessing Tuple Elements

Just like lists and strings, you can use indexing to access specific elements of a tuple. You can also use slicing to grab parts of a tuple. While you can read the values, you can’t change them directly.

 

numbers = (1, 2, 3, 4, 5)
print(numbers[0])     # 1
print(numbers[-1])    # 5
print(numbers[1:4])   # (2, 3, 4)

 

Tuple Packing and Unpacking

One of the coolest things about tuples is that you can group multiple values into a tuple (called packing) and then split them back out into individual variables (called unpacking). It makes your code cleaner and easier to read, especially when working with functions that return more than one value.

 

# Packing
point = (3, 7)

# Unpacking
x, y = point
print("x:", x)   # 3
print("y:", y)   # 7

 

When to Use Tuples

Because you can’t change them, tuples are great for storing data that should remain constant — like coordinates, color values, or config settings. They also use less memory and are slightly faster than lists, so they’re helpful in performance-sensitive code.

 

Interactive Exercise: Packing and Unpacking

Try creating a tuple with three values and unpacking them into separate variables. Change the values and see how the unpacked results update.

 


# Create a tuple
info = ("Alice", 25, "Engineer")

# Unpack values
name, age, job = info
print("Name:", name)
print("Age:", age)
print("Job:", job)

 
Use commas to unpack each element into its own variable.
 

Interactive Exercise: Tuple Indexing

Practice grabbing specific items from a tuple using both positive and negative indexes, as well as slicing to get a section of the tuple.

 


numbers = (10, 20, 30, 40, 50)

print("First element:", numbers[0])
print("Last element:", numbers[-1])
print("Middle slice:", numbers[1:4])

 
Remember that slicing works just like with lists and strings.
 

Tuples may seem simple, but they’re extremely useful when you need to group values that won’t change. By understanding when and how to use them, you’ll be able to build cleaner, safer, and more efficient Python programs. Up next — we’ll look at dictionaries, which let you store data using key-value pairs.