Home Course Roadmap
Home / Python Foundations / Lesson 20
Lesson 20 · Data Collections Beginner

Python Tuples

Learn how Python tuples store ordered collections of values, why tuples are immutable, how tuple unpacking works, and when tuples are more appropriate than lists.

35–45 minutes Python Foundations Beginner
0%

Learning Objectives

By the end of this lesson, you will be able to:

  • Understand what tuples are and how they differ from lists.
  • Create tuples using parentheses and commas.
  • Access tuple elements using indexing and slicing.
  • Understand tuple immutability.
  • Unpack tuple values into separate variables.
  • Loop through tuples and perform membership tests.
  • Use tuple methods such as count() and index().
  • Choose appropriately between lists and tuples.
01

What Are Tuples?

A tuple is a Python collection used to store multiple values in a single variable.

Tuples are similar to lists because they are ordered collections and support indexing, slicing, looping, and membership testing.

The major difference is that tuples are immutable.

Once a tuple has been created, its elements cannot be changed, added, or removed.

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

print(colors)
Output
('red', 'green', 'blue')
Key Idea

A tuple is an ordered collection whose contents cannot be changed after creation.

02

Why Tuples Matter

Tuples are useful when a group of values should remain fixed.

For example, the coordinates of a location can be represented as a tuple:

Coordinates
location = (30.1575, 71.5249)

print(location)

If the program treats the latitude and longitude as one fixed pair, a tuple is a natural choice.

Tuples are also commonly used for fixed records, function returns, dictionary keys in suitable cases, and data that should not accidentally be modified.

03

Creating Tuples

Tuples are commonly written using parentheses ().

Different Tuples
numbers = (10, 20, 30)

names = ("Ali", "Sara", "Ahmed")

mixed = ("Python", 25, 3.5, True)

empty = ()

Python also allows tuple creation without explicitly writing parentheses. The comma is what makes the structure a tuple.

Tuple Packing
student = "Ali", 25, "Python"

print(student)
print(type(student))
Output
('Ali', 25, 'Python')
<class 'tuple'>
04

Single-Item Tuples

Creating a tuple containing one item requires a trailing comma.

Correct
single = ("Python",)

print(type(single))
Output
<class 'tuple'>

Without the comma, parentheses simply group an expression.

Not a Tuple
value = ("Python")

print(type(value))
Output
<class 'str'>
Remember

For a one-item tuple, the comma is essential: ("Python",).

05

Accessing Tuple Items

Tuples use zero-based indexing, just like lists.

Indexing
languages = ("Python", "Java", "C++")

print(languages[0])
print(languages[1])
print(languages[2])
Output
Python
Java
C++

The indexing rules are the same as those used with lists.

06

Negative Indexing

Negative indexes allow us to access tuple elements from the end.

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

print(colors[-1])
print(colors[-2])
Output
yellow
blue

Therefore:

  • -1 → last item
  • -2 → second-last item
  • -3 → third-last item
07

Tuple Slicing

Tuples support slicing using the same syntax used with strings and lists.

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

print(numbers[1:4])
print(numbers[:3])
print(numbers[2:])
print(numbers[::2])
Output
(20, 30, 40)
(10, 20, 30)
(30, 40, 50)
(10, 30, 50)

The stop index is excluded from the result.

08

Tuple Immutability

The most important characteristic of a tuple is immutability.

You cannot directly change an existing tuple element.

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

colors[1] = "yellow"
Result

This raises a TypeError because tuple elements cannot be reassigned.

You also cannot use methods such as append(), remove(), or clear() on a tuple.

Why Is This Useful?

Immutability helps protect data from accidental modification.

09

Tuple Unpacking

Tuple unpacking allows us to assign tuple elements to separate variables.

Python
student = ("Ali", 25, "Python")

name, age, course = student

print(name)
print(age)
print(course)
Output
Ali
25
Python

Python assigns each tuple value to the corresponding variable.

Important

The number of variables must normally match the number of values being unpacked.

10

Extended Unpacking

Python provides the * operator for collecting multiple remaining values during unpacking.

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

first, *middle, last = numbers

print(first)
print(middle)
print(last)
Output
10
[20, 30, 40]
50

Notice that the starred variable, middle, becomes a list containing the remaining values.

11

Looping Through Tuples

We can use a for loop to process every element of a tuple.

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

for color in colors:
    print(color)
Output
red
green
blue

Since tuples are iterable, they work naturally with loops.

12

Membership Testing

The in and not in operators work with tuples.

Python
languages = ("Python", "Java", "C++")

print("Python" in languages)
print("PHP" in languages)
print("PHP" not in languages)
Output
True
False
True
13

Finding Tuple Length

The len() function returns the number of elements in a tuple.

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

print(len(numbers))
Output
4
14

Tuple Methods

Tuples have fewer methods than lists because they cannot be modified.

count()

count() tells us how many times a value appears in a tuple.

count()
numbers = (1, 2, 2, 3, 2, 4)

print(numbers.count(2))
Output
3

index()

index() returns the position of the first matching value.

index()
languages = ("Python", "Java", "C++")

print(languages.index("Java"))
Output
1
Be Careful

If the requested value does not exist, index() raises a ValueError.

15

Lists vs Tuples

Lists and tuples are both ordered collections, but they are designed for slightly different purposes.

Key Differences

  • List: mutable and can be changed.
  • Tuple: immutable and cannot be changed.
  • List: uses [].
  • Tuple: commonly uses ().
  • List: provides many modification methods.
  • Tuple: provides only a small number of methods.
Comparison
shopping_cart = ["Laptop", "Mouse"]

coordinates = (30.15, 71.52)

A shopping cart is likely to change, so a list is appropriate. Coordinates representing one fixed location can naturally be represented as a tuple.

16

Nested Tuples

Tuples can contain other tuples.

Nested Tuples
locations = (
    ("Multan", "Pakistan"),
    ("Lahore", "Pakistan"),
    ("Karachi", "Pakistan")
)

print(locations[0])
print(locations[1][0])
Output
('Multan', 'Pakistan')
Lahore

Nested structures are useful for representing structured, fixed collections of information.

17

Tuples with Mixed Data Types

Like lists, tuples can contain different data types.

Python
profile = (
    "Ali",
    25,
    3.8,
    True
)

print(profile)
Output
('Ali', 25, 3.8, True)

The important point is that the tuple itself remains immutable even when it contains different types.

18

Practical Real-World Examples

Example 1 — Product Information

Product Record
product = ("Laptop", 125000, "Electronics")

name, price, category = product

print("Product:", name)
print("Price:", price)
print("Category:", category)

Example 2 — Returning Multiple Values

Functions can return multiple values, which Python packs into a tuple.

Function Example
def calculate(a, b):
    total = a + b
    difference = a - b
    return total, difference


result = calculate(20, 5)

print(result)
Output
(25, 15)

This becomes especially useful when we later learn more deeply about functions and multiple return values.

Example 3 — Fixed RGB Color

RGB Values
red = (255, 0, 0)

print("Red:", red[0])
print("Green:", red[1])
print("Blue:", red[2])
19

Common Tuple Mistakes

Mistake 1 — Forgetting the Comma

value = ("Python")

print(type(value))

This creates a string, not a tuple.

Correct:

value = ("Python",)

Mistake 2 — Trying to Modify a Tuple

numbers = (1, 2, 3)

numbers[0] = 100

This raises a TypeError.

Mistake 3 — Wrong Number of Unpacking Variables

data = ("Ali", 25, "Python")

name, age = data

There are three values but only two variables, so Python raises a ValueError.

Mistake 4 — Expecting List Methods

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

colors.append("yellow")

Tuples do not have append() because they cannot be modified.

20

Practice Exercises

Exercise 1 — Create a Tuple

Create a tuple containing five programming languages and print it.

Exercise 2 — Access Items

Create a tuple of five cities. Print the first, third, and last city.

Exercise 3 — Negative Indexing

Create a tuple of six numbers and print the last three values using negative indexing.

Exercise 4 — Slicing

Create a tuple containing ten numbers and extract the middle five values using slicing.

Exercise 5 — Unpacking

Create a tuple containing a student's name, age, and grade. Unpack the values into separate variables.

Exercise 6 — Membership

Create a tuple of programming languages and check whether Python exists in it.

Exercise 7 — count() and index()

Create a tuple with repeated numbers and practice both count() and index().

21

Mini Challenge — Student Record

Build a simple student record using a tuple.

Your program should:

  • Store the student's name, age, course, and grade in a tuple.
  • Unpack the tuple into separate variables.
  • Display each value.
  • Check whether a specific value exists in the tuple.
  • Display the total number of values.
Challenge Starter
student = (
    "Ali",
    22,
    "Python",
    "A"
)

# Unpack the tuple here

# Display the student information

# Check whether "Python" exists

# Display the number of values
Challenge Goal

Try solving the challenge without converting the tuple into a list. The purpose is to practice tuple indexing, unpacking, membership testing, and len().

22

Quick Knowledge Check

1. Which brackets are commonly used to create a tuple?

2. What makes a tuple different from a list?

3. Which is a valid one-item tuple?

4. What does tuple[-1] access?

5. Which method counts occurrences of a value?

6. What does tuple unpacking do?

7. What happens here? x = (1, 2, 3); x[0] = 10

8. Which operator checks whether a value exists in a tuple?

23

Lesson Summary

Tuples are an important Python collection type, especially when data should remain fixed.

  • Tuples store multiple values in a single variable.
  • Tuples are ordered and support indexing.
  • Tuples are commonly written using ().
  • A one-item tuple requires a trailing comma.
  • Tuples support positive and negative indexing.
  • Tuples support slicing.
  • Tuples are immutable.
  • Tuple values can be unpacked into variables.
  • The * operator can be used for extended unpacking.
  • Tuples support loops and membership testing.
  • count() counts occurrences.
  • index() finds the first matching position.
  • Lists are generally better for collections that need to change.
  • Tuples are useful for fixed collections of values.
Key Takeaway

The biggest concept to remember is: lists are mutable, while tuples are immutable. Choosing the correct collection type makes your programs safer, clearer, and easier to maintain.

Ready for the Next Lesson?

You've learned how Python tuples work, how to unpack them, and when to use them instead of lists.