Nearby lessons

65 of 159

Python - Tuples

📌 What You Will Learn
  • Understand what a tuple is and why it is immutable
  • Create tuples including empty and single-valued tuples
  • Access tuple items with indexing, negative indexes and slicing
  • Use tuple functions like len(), count(), index(), sorted(), min() and max()
  • Pack and unpack tuples including the * operator
  • Compare tuples with lists and use generator expressions

Introduction

A Tuple is exactly the same as a List, except that it is immutable.

Once we create a tuple object, we cannot perform any changes to that object.

Because of this property, a tuple is called the Read-Only version of List.

When Should We Use a Tuple?

If our data is fixed and never changes, then we should use a Tuple.

Since tuple objects are immutable, they provide better protection for fixed data.

Features of Tuple

1. Insertion Order is Preserved

The elements are stored in the same order in which they are inserted.

2. Duplicate Objects are Allowed

A tuple can contain duplicate values.

3. Heterogeneous Objects are Allowed

A tuple can store different types of data together.

Example - Heterogeneous Tuple

Loading editor…

Explanation

The above tuple contains:

  • Integer values
  • String values
  • Duplicate value (10)

Tuple is Immutable

Tuple objects are immutable.

Once a tuple is created, its contents cannot be changed.

Because of this property, a tuple is called the Read-Only version of List.

Index in Tuple

Since insertion order is preserved, indexes play an important role in tuples.

Indexes help us access elements and differentiate duplicate objects.

Python supports two types of indexing:

  • Positive Index
  • Negative Index

Positive and Negative Index

Positive Index Negative Index
Starts from left to right. Starts from right to left.
First index is 0. Last index is -1.

Example - Tuple Index

Element 10 20 30 40
Positive Index 0 1 2 3
Negative Index -4 -3 -2 -1
Loading editor…

Representation of Tuple

Tuple elements are represented using parentheses ().

Each element is separated by a comma (,).

Parentheses are optional, but it is recommended to use them.

Example - Tuple Representation

Loading editor…

Creating an Empty Tuple

An empty tuple can be created using empty parentheses.

Example - Empty Tuple

Loading editor…

Single-Valued Tuple

Special care is required while creating a tuple with only one element.

The value must end with a comma (,).

Otherwise, Python will not treat it as a tuple.

Incorrect Example

Loading editor…

Correct Example

Loading editor…

Accessing Tuple Elements

Tuple elements can be accessed in two ways:

  1. Using Index
  2. Using Slice Operator

Python supports both positive and negative indexing.

Example - Positive Index

Loading editor…

Example - Negative Index

Loading editor…

Tuple Slicing

We can access multiple elements from a tuple using the slice operator.

Syntax

Loading editor…

Example 1 - Slice Operator

Loading editor…

Example 2 - Complete Tuple

Loading editor…

Tuple Immutability

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

Once a tuple is created, its elements cannot be modified, added, or removed.

If we try to change any element, Python raises an error.

Example 1 - Modify a Tuple Element

Loading editor…

Explanation

The tuple object is immutable.

Therefore, existing elements cannot be modified after the tuple is created.

Example 2 - Add a New Element

Loading editor…

Explanation

Unlike lists, tuples do not provide methods such as append(), extend(), or insert().

This is because tuples are immutable.

Example 3 - Delete an Element

Loading editor…

Deleting a Tuple

Although tuple elements cannot be deleted individually, the complete tuple object can be deleted.

Example - Delete Complete Tuple

Loading editor…

Tuple Operators

Python supports several operators for tuples.

The most commonly used tuple operators are:

  • Concatenation Operator (+)
  • Repetition Operator (*)

Concatenation Operator (+)

The + operator joins two tuples and returns a new tuple.

The original tuples are not modified.

Syntax

Loading editor…

Example 1 - Join Two Tuples

Loading editor…

Example 2 - Join String Tuples

Loading editor…

Example 3 - Invalid Concatenation

Loading editor…

Repetition Operator (*)

The * operator repeats the elements of a tuple.

A new tuple containing repeated elements is returned.

Syntax

Loading editor…

Example 1 - Repeat Tuple

Loading editor…

Example 2 - Repeat String Tuple

Loading editor…

Explanation

The original tuple is not modified.

A new tuple is created with repeated elements.

Difference Between + and * Operators

+ *
Joins two tuples. Repeats tuple elements.
Requires two tuples. Requires one tuple and an integer.
Returns a combined tuple. Returns a repeated tuple.

Real World Usage

Tuples are commonly used in:

  • Configuration data
  • Coordinate values
  • Fixed records
  • Database results
  • Function return values

Tuple Functions

Python provides several built-in functions and methods to get information about a tuple.

The most commonly used tuple functions are:

  • len()
  • count()
  • index()
  • sorted()
  • min()
  • max()

These functions help us find the size, search elements, count duplicate values, sort elements, and find minimum and maximum values.

len() Function

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

Syntax:

Syntax

Loading editor…

Example 1 - Length of Tuple

Loading editor…

Example 2 - Empty Tuple

Loading editor…

Example 3 - Heterogeneous Tuple

Loading editor…

Explanation

The len() function counts every element present in the tuple.

The data type of the elements does not affect the result.

count() Method

The count() method returns the number of occurrences of a specified element.

Syntax:

Syntax

Loading editor…

Example 1 - Count Duplicate Elements

Loading editor…

Example 2 - Count String Elements

Loading editor…

Example 3 - Element Not Present

Loading editor…

Explanation

If the specified element is not present, the count() method returns 0.

index() Method

The index() method returns the index of the first occurrence of the specified element.

Syntax:

Syntax

Loading editor…

Example 1 - Find Index

Loading editor…

Example 2 - Duplicate Elements

Loading editor…

Explanation

If duplicate elements are available, the index of the first occurrence is returned.

Example 3 - Element Not Present

Loading editor…

sorted() Function

The sorted() function sorts tuple elements and returns them as a new list.

The original tuple remains unchanged.

Syntax:

Syntax

Loading editor…

Example 1 - Ascending Order

Loading editor…

Example 2 - Descending Order

Loading editor…

Explanation

The return type of sorted() is a list, not a tuple.

The original tuple is not modified.

min() Function

The min() function returns the smallest element from the tuple.

Syntax

Loading editor…

Example

Loading editor…

max() Function

The max() function returns the largest element from the tuple.

Syntax

Loading editor…

Example

Loading editor…

Difference Between count() and index()

count() index()
Returns the number of occurrences. Returns the index of the first occurrence.
Returns 0 if the element is not available. Raises ValueError if the element is not available.

Real World Usage

Tuple functions are commonly used in:

  • Searching records
  • Finding duplicate values
  • Statistical calculations
  • Sorting reports
  • Finding minimum and maximum values

Tuple Packing

Tuple Packing is the process of assigning multiple values to a single tuple.

Python automatically packs all values into a tuple.

Parentheses are optional while packing a tuple.

Syntax

Loading editor…

Example 1 - Tuple Packing

Loading editor…

Explanation

Python automatically packs all the given values into a tuple object.

This process is called Tuple Packing.

Example 2 - Packing Different Data Types

Loading editor…

Example 3 - Packing Without Parentheses

Loading editor…

Tuple Unpacking

Tuple Unpacking is the process of assigning tuple elements to individual variables.

The number of variables must be equal to the number of tuple elements.

Syntax

Loading editor…

Example 1 - Tuple Unpacking

Loading editor…

Explanation

The first value is assigned to the first variable.

The second value is assigned to the second variable.

The third value is assigned to the third variable.

Example 2 - Unpacking Student Information

Loading editor…

Example 3 - Swap Two Variables

Tuple packing and unpacking are commonly used to swap two variables without using a temporary variable.

Program

Loading editor…

Example 4 - Invalid Unpacking

Loading editor…

Explanation

The number of variables and tuple elements must be the same.

Otherwise, Python raises a ValueError.

Using * Operator in Tuple Unpacking

The * operator collects multiple remaining elements into a list.

This is useful when the number of tuple elements is greater than the number of variables.

Example 1 - Collect Remaining Elements

Loading editor…

Example 2 - Collect Middle Elements

Loading editor…

Example 3 - Collect Initial Elements

Loading editor…

Difference Between Tuple Packing and Unpacking

Tuple Packing Tuple Unpacking
Multiple values are stored in one tuple. Tuple elements are assigned to variables.
Creates a tuple. Extracts values from a tuple.
One tuple object is created. Multiple variables receive values.

Real World Usage

Tuple packing and unpacking are commonly used in:

  • Returning multiple values from functions.
  • Swapping variables.
  • Processing database records.
  • Reading CSV and Excel data.
  • Handling multiple values efficiently.

Tuple Comprehension

Unlike lists, Python does not support tuple comprehension.

If we write an expression similar to list comprehension using parentheses, Python creates a Generator Object instead of a tuple.

Therefore, tuple comprehension is not available in Python.

Syntax

Loading editor…

Example 1 - Generator Object

Loading editor…

Explanation

The above expression does not create a tuple.

Instead, it creates a generator object.

The values are generated one by one whenever required.

Convert Generator to Tuple

If we want a tuple from a generator object, we can pass the generator to the tuple() function.

Example 2 - Convert Generator to Tuple

Loading editor…

Generator Object

A generator is a special type of iterable.

It generates values one at a time instead of storing all values in memory.

This helps in saving memory when working with a large amount of data.

Example 3 - Iterate Generator

Loading editor…

Advantages of Generator

  • Consumes less memory.
  • Generates values only when required.
  • Suitable for large data processing.
  • Improves program performance.

List Comprehension vs Tuple Expression

List Comprehension Tuple Expression
Creates a List. Creates a Generator Object.
Uses square brackets []. Uses parentheses ().
Stores all values immediately. Generates values one by one.

Difference Between List and Tuple

List Tuple
Mutable Immutable
Uses square brackets []. Uses parentheses ().
Supports append(), extend(), insert(), remove(), etc. Does not support modification methods.
Suitable for frequently changing data. Suitable for fixed data.
Consumes more memory. Consumes less memory.
Slightly slower. Slightly faster.

When Should We Use List?

  • When data changes frequently.
  • When elements need to be added or removed.
  • When the collection needs to be modified.

When Should We Use Tuple?

  • When data is fixed.
  • When values should not be modified.
  • When better performance and less memory usage are required.
📝 Key Takeaways
  • A tuple is an immutable, read-only version of a list
  • Tuple elements cannot be modified, added or deleted after creation
  • Tuple functions include len(), count(), index(), sorted(), min() and max()
  • Tuple packing groups values and unpacking assigns them to variables
  • Tuples preserve insertion order and allow duplicate values

🧠 Test Your Knowledge

40 Questions
Progress: 0 / 40

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.