Python Programming for Beginners

Chapter 8: Python Tuples – Creating, Accessing and Using Tuples

8.1 Introduction

In the previous chapter, we learned about lists, which are used to store multiple values in a single variable.

Python also provides another useful collection type called a tuple.

A tuple is similar to a list, but there is an important difference:

Lists are mutable, while tuples are immutable.

This means that after creating a tuple, its individual elements cannot normally be changed, added, or removed.

Tuples are useful when you want to store a collection of values that should remain unchanged.

In this chapter, you will learn:

  • What tuples are
  • How to create tuples
  • Accessing tuple elements
  • Negative indexing
  • Tuple slicing
  • Tuple unpacking
  • Looping through tuples
  • Tuple methods
  • Nested tuples
  • Converting between lists and tuples
  • Returning multiple values from functions
  • Practical examples and projects

8.2 What is a Tuple?

A tuple is an ordered collection of items.

Tuples are generally written using parentheses ().

Example:

 

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

 

Output:

(10, 20, 30, 40, 50)

 

Like lists, tuple elements have indexes beginning from 0.

8.3 Creating a Tuple

The simplest way to create a tuple is to use parentheses.

 

fruits = ("Apple", "Banana", "Mango") print(fruits)

 

Output:

('Apple', 'Banana', 'Mango')

 

You can also create a tuple containing numbers:

 

marks = (80, 75, 92, 88)

 

8.4 Empty Tuple

An empty tuple contains no elements.

 

data = () print(data)

 

Output:

()

 

You can check its length:

 

print(len(data))

 

Output:

0

 

8.5 Single-Item Tuple

There is an important rule when creating a tuple with only one item.

This is not a tuple:

 

number = (10)

 

Python treats (10) as an ordinary integer expression.

To create a single-item tuple, you need a comma:

 

number = (10,) print(type(number))

 

Output:

<class 'tuple'>

 

The comma is what makes it a tuple.

8.6 Tuple Without Parentheses

Python also allows you to create a tuple without parentheses.

 

numbers = 10, 20, 30 print(numbers)

 

Output:

(10, 20, 30)

 

This is called tuple packing.

However, using parentheses often makes the code easier to read.

8.7 Tuple Indexing

Tuple indexing works like list indexing.

Consider:

 

fruits = ("Apple", "Banana", "Mango", "Orange")

 

The indexes are:

IndexValue
0Apple
1Banana
2Mango
3Orange

Access an element using its index:

 

print(fruits[0]) print(fruits[2])

 

Output:

Apple Mango

 

8.8 Negative Indexing

Tuples also support negative indexing.

The last item has index -1.

 

fruits = ("Apple", "Banana", "Mango", "Orange") print(fruits[-1]) print(fruits[-2])

 

Output:

Orange Mango

 

Negative indexes count from the end of the tuple.

8.9 Tuple Slicing

You can extract a portion of a tuple using slicing.

Syntax:

 

tuple[start:stop]

 

Example:

 

numbers = (10, 20, 30, 40, 50) print(numbers[1:4])

 

Output:

(20, 30, 40)

 

The ending index is not included.

8.10 Slicing from the Beginning

 

numbers = (10, 20, 30, 40, 50) print(numbers[:3])

 

Output:

(10, 20, 30)

 

8.11 Slicing to the End

 

numbers = (10, 20, 30, 40, 50) print(numbers[2:])

 

Output:

(30, 40, 50)

 

8.12 Reversing a Tuple

You can use slicing to create a reversed tuple.

 

numbers = (10, 20, 30, 40, 50) print(numbers[::-1])

 

Output:

(50, 40, 30, 20, 10)

 

8.13 Tuples Are Immutable

The most important property of a tuple is that it is immutable.

Consider:

 

numbers = (10, 20, 30) numbers[1] = 50

 

This produces a TypeError.

You cannot directly change an existing tuple element.

With a list, this is allowed:

 

numbers = [10, 20, 30] numbers[1] = 50 print(numbers)

 

Output:

[10, 50, 30]

 

But with a tuple:

 

numbers = (10, 20, 30)

 

the elements cannot be reassigned.

8.14 Why Are Tuples Immutable?

Immutability can be useful when data should not accidentally be changed.

For example:

 

coordinates = (23.25, 77.41)

 

If these values represent a fixed coordinate pair, a tuple communicates that the collection is intended to remain unchanged.

Tuples can also be useful for fixed configuration values and records.

8.15 Tuple Length

Use the len() function to find the number of elements.

 

fruits = ("Apple", "Banana", "Mango") print(len(fruits))

 

Output:

3

 

8.16 Checking an Item in a Tuple

Use the in operator.

 

fruits = ("Apple", "Banana", "Mango") if "Mango" in fruits:    print("Mango is available")

 

Output:

Mango is available

 

You can also use not in.

 

if "Orange" not in fruits:    print("Orange is not available")

 

8.17 Looping Through a Tuple

A for loop can be used to process each tuple element.

 

subjects = ("Maths", "Science", "English", "Computer") for subject in subjects:    print(subject)

 

Output:

Maths Science English Computer

 

8.18 Using while with a Tuple

You can also use a while loop.

 

numbers = (10, 20, 30, 40) i = 0 while i < len(numbers):    print(numbers[i])    i += 1

 

Output:

10 20 30 40

 

8.19 Tuple Methods

Because tuples are immutable, they have fewer methods than lists.

The two commonly used tuple methods are:

  • count()
  • index()

8.20 The count() Method

The count() method returns the number of times a value appears in a tuple.

 

numbers = (10, 20, 10, 30, 10) print(numbers.count(10))

 

Output:

3

 

8.21 The index() Method

The index() method returns the index of the first occurrence of a value.

 

fruits = ("Apple", "Banana", "Mango") print(fruits.index("Banana"))

 

Output:

1

 

If the value does not exist, Python raises a ValueError.

You can check first:

 

if "Orange" in fruits:    print(fruits.index("Orange"))

 

8.22 Tuple Concatenation

Two tuples can be combined using the + operator.

 

first = (1, 2, 3) second = (4, 5, 6) result = first + second print(result)

 

Output:

(1, 2, 3, 4, 5, 6)

 

The original tuples are not modified.

A new tuple is created.

8.23 Repeating a Tuple

The * operator can repeat a tuple.

 

numbers = (1, 2, 3) result = numbers * 3 print(result)

 

Output:

(1, 2, 3, 1, 2, 3, 1, 2, 3)

 

8.24 Tuple Packing

Putting multiple values into a tuple is called tuple packing.

 

student = "Aman", 20, "Delhi" print(student)

 

Output:

('Aman', 20, 'Delhi')

 

Python automatically creates a tuple.

8.25 Tuple Unpacking

Tuple unpacking is the opposite of tuple packing.

You can assign tuple elements to separate variables.

 

student = ("Aman", 20, "Delhi") name, age, city = student print(name) print(age) print(city)

 

Output:

Aman 20 Delhi

 

The number of variables should normally match the number of tuple elements.

8.26 Extended Tuple Unpacking

Python also supports the * operator during unpacking.

Example:

 

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 receives a list.

8.27 Swapping Variables Using Tuples

Python makes variable swapping simple.

 

a = 10 b = 20 a, b = b, a print(a) print(b)

 

Output:

20 10

 

This works because Python packs the right-hand values and then unpacks them into the variables.

8.28 Nested Tuples

A tuple can contain other tuples.

Example:

 

students = (    ("Aman", 85),    ("Ravi", 78),    ("Neha", 92) ) print(students)

 

You can access nested values:

 

print(students[0][0]) print(students[0][1])

 

Output:

Aman 85

 

8.29 Looping Through Nested Tuples

 

students = (    ("Aman", 85),    ("Ravi", 78),    ("Neha", 92) ) for name, marks in students:    print("Name:", name)    print("Marks:", marks)

 

Output:

Name: Aman Marks: 85 Name: Ravi Marks: 78 Name: Neha Marks: 92

 

Tuple unpacking makes this code easy to read.

8.30 Converting a List into a Tuple

The tuple() function can convert an iterable into a tuple.

 

fruits = ["Apple", "Banana", "Mango"] fruits_tuple = tuple(fruits) print(fruits_tuple)

 

Output:

('Apple', 'Banana', 'Mango')

 

8.31 Converting a Tuple into a List

You can convert a tuple into a list using list().

 

numbers = (10, 20, 30) numbers_list = list(numbers) print(numbers_list)

 

Output:

[10, 20, 30]

 

This can be useful if you need to modify the data.

8.32 Modifying a Tuple Indirectly

A tuple itself cannot be modified directly.

However, you can create a new tuple.

 

numbers = (10, 20, 30) numbers = numbers + (40,) print(numbers)

 

Output:

(10, 20, 30, 40)

 

The original tuple was not changed. A new tuple was created and assigned to the variable.

8.33 Tuple with Different Data Types

A tuple can contain different types of values.

 

student = ("Aman", 20, 85.5, True) print(student)

 

Output:

('Aman', 20, 85.5, True)

 

This is similar to a list.

8.34 Comparing Lists and Tuples

FeatureListTuple
Syntax[]()
OrderedYesYes
MutableYesNo
Allows duplicatesYesYes
IndexingYesYes
SlicingYesYes
append()YesNo
remove()YesNo
count()YesYes
index()YesYes

Example

List:

 

numbers = [10, 20, 30]

 

Tuple:

 

numbers = (10, 20, 30)

 

Choose a list when the collection needs to change.

Choose a tuple when the collection is intended to remain fixed.

8.35 Finding Minimum and Maximum

Tuples containing comparable numeric values can be used with min() and max().

 

numbers = (10, 50, 20, 40, 30) print("Minimum:", min(numbers)) print("Maximum:", max(numbers))

 

Output:

Minimum: 10 Maximum: 50

 

8.36 Calculating the Sum

For numeric tuples, sum() can be used.

 

marks = (80, 75, 90, 85) print("Total:", sum(marks))

 

Output:

Total: 330

 

Average can be calculated as:

 

average = sum(marks) / len(marks) print("Average:", average)

 

8.37 Tuple as a Function Return Value

Tuples are commonly used when a function needs to return multiple values.

Example:

 

def calculate(a, b):    total = a + b    difference = a - b    return total, difference result = calculate(20, 5) print(result)

 

Output:

(25, 15)

 

You can also unpack the result:

 

total, difference = calculate(20, 5) print("Total:", total) print("Difference:", difference)

 

Output:

Total: 25 Difference: 15

 

8.38 Example: Student Record

A tuple can represent a fixed student record.

 

student = ("Aman", 20, "Computer Science", 85) print("Name:", student[0]) print("Age:", student[1]) print("Course:", student[2]) print("Marks:", student[3])

 

Output:

Name: Aman Age: 20 Course: Computer Science Marks: 85

 

8.39 Example: Coordinates

Tuples are useful for representing fixed coordinate pairs.

 

point = (10, 20) x, y = point print("X:", x) print("Y:", y)

 

Output:

X: 10 Y: 20

 

8.40 Example: RGB Color Values

A fixed RGB value can be represented as a tuple.

 

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

 

Output:

Red: 255 Green: 0 Blue: 0

 

8.41 Example: Days of the Week

If the values should remain fixed, a tuple can be useful.

 

days = (    "Monday",    "Tuesday",    "Wednesday",    "Thursday",    "Friday",    "Saturday",    "Sunday" ) for day in days:    print(day)

 

8.42 Example: Menu Items

A fixed menu can also be stored in a tuple.

 

menu = (    "Pizza",    "Burger",    "Sandwich",    "Pasta" ) for item in menu:    print(item)

 

8.43 Common Tuple Mistakes

Mistake 1: Forgetting the comma in a single-item tuple

Incorrect:

 

value = (10)

 

Correct:

 

value = (10,)

 

Mistake 2: Trying to modify a tuple

Incorrect:

 

numbers = (10, 20, 30) numbers[0] = 100

 

A tuple is immutable, so this raises a TypeError.

If the data needs to change frequently, consider using a list.

Mistake 3: Incorrect unpacking

Consider:

 

data = (10, 20, 30)

 

This will fail:

 

a, b = data

 

because there are three values but only two variables.

Correct:

 

a, b, c = data

 

8.44 Mini Project: Student Result Analyzer

 

def calculate_result(marks):    total = sum(marks)    average = total / len(marks)    return total, average student = ("Aman", (85, 78, 92, 88)) name, marks = student total, average = calculate_result(marks) print("Student:", name) print("Marks:", marks) print("Total:", total) print("Average:", average)

 

Output:

Student: Aman Marks: (85, 78, 92, 88) Total: 343 Average: 85.75

 

This example demonstrates:

  • Nested tuples
  • Tuple unpacking
  • Functions
  • Returning multiple values
  • sum()
  • len()

8.45 Mini Project: Coordinate Manager

 

points = (    (10, 20),    (30, 40),    (50, 60) ) for x, y in points:    print("X =", x, "Y =", y)

 

Output:

X = 10 Y = 20 X = 30 Y = 40 X = 50 Y = 60

 

8.46 Mini Project: Contact Record

 

contact = (    "Aman Sharma",    "9876543210",    "aman@example.com" ) name, phone, email = contact print("Name:", name) print("Phone:", phone) print("Email:", email)

 

This demonstrates how a tuple can represent a fixed group of related values.

8.47 When Should You Use a Tuple?

Use a tuple when:

  • The data should not normally change.
  • You want to represent a fixed collection.
  • You need simple unpacking.
  • A function needs to return multiple values.
  • You want to communicate that a collection is intended to be fixed.

Examples include:

 

coordinates = (10, 20)

 

 

rgb = (255, 255, 255)

 

 

months = ("January", "February", "March")

 

8.48 When Should You Use a List?

Use a list when:

  • Items need to be added.
  • Items need to be removed.
  • Items need to be modified.
  • The collection changes during program execution.

Example:

 

shopping_cart = ["Milk", "Bread"]

 

You may add or remove products later, so a list is appropriate.

8.49 Chapter Summary

In this chapter, you learned:

  • What tuples are
  • Creating tuples
  • Empty tuples
  • Single-item tuples
  • Tuple indexing
  • Negative indexing
  • Tuple slicing
  • Tuple immutability
  • Tuple length
  • Searching tuple elements
  • count()
  • index()
  • Tuple concatenation
  • Tuple repetition
  • Tuple packing
  • Tuple unpacking
  • Extended unpacking
  • Nested tuples
  • List-to-tuple conversion
  • Tuple-to-list conversion
  • Using tuples with functions
  • Returning multiple values
  • Practical uses of tuples
  • Differences between lists and tuples

The key concept to remember is:

A list is mutable, while a tuple is immutable.

Quick Revision Questions

1. What is a tuple?

A tuple is an ordered collection of values that cannot normally be modified after creation.

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

Parentheses ().

3. What is the index of the first tuple element?

0.

4. Are tuples mutable?

No. Tuples are immutable.

5. How do you create a single-item tuple?

 

value = (10,)

 

6. Which method counts occurrences of a value?

count().

7. Which method finds the index of a value?

index().

8. Can tuples contain duplicate values?

Yes.

9. Can tuples contain different data types?

Yes.

10. What is tuple unpacking?

Assigning tuple elements to separate variables.

Example:

 

a, b, c = (10, 20, 30)

 

11. How can you convert a list into a tuple?

 

tuple(my_list)

 

12. How can you convert a tuple into a list?

 

list(my_tuple)

 

Practice Exercises

Exercise 1: Create a Tuple

Create a tuple containing five programming languages and display it.

Exercise 2: Access Elements

Create a tuple of five numbers and display the first, third, and last elements.

Exercise 3: Negative Indexing

Create a tuple of fruits and display the last two fruits using negative indexing.

Exercise 4: Tuple Slicing

Create a tuple containing numbers from 1 to 10 and display numbers from index 2 to index 6.

Exercise 5: Count Values

Create a tuple containing duplicate numbers and use count() to find how many times a particular number appears.

Exercise 6: Tuple Unpacking

Create a tuple containing a student's name, age, and marks. Unpack it into three variables.

Exercise 7: Nested Tuples

Create a tuple containing three student records. Each record should contain a name and marks.

Exercise 8: List to Tuple

Create a list of five subjects and convert it into a tuple.

Exercise 9: Tuple to List

Create a tuple of five numbers and convert it into a list.

Exercise 10: Function Return

Create a function that accepts two numbers and returns their sum and difference as a tuple.

Chapter Activity

Create a Student Record System using Tuples.

Each student record should contain:

  • Student name
  • Age
  • Class
  • Marks

Example:

 

students = (    ("Aman", 15, 10, 85),    ("Ravi", 16, 10, 78),    ("Neha", 15, 10, 92) )

 

Your program should:

  1. Display all student records.
  2. Display each student's name and marks.
  3. Calculate the highest marks.
  4. Calculate the average marks.
  5. Search for a student by name.
  6. Use tuple unpacking wherever appropriate.