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

🐍Code Cell
1t = (10, "A", "B", 20, 10)
2 
3print(t)
Output
(10, 'A', 'B', 20, 10)

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
🐍Code Cell
1t = (10, 20, 30, 40)
Output
No output captured.

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

🐍Code Cell
1t = 10, 20, 30, 40
2 
3print(t)
4 
5print(type(t))
Output
(10, 20, 30, 40)

Creating an Empty Tuple

An empty tuple can be created using empty parentheses.

Example - Empty Tuple

🐍Code Cell
1t = ()
2 
3print(type(t))
Output
No output captured.

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

🐍Code Cell
1t = (10)
2 
3print(t)
4 
5print(type(t))
Output
10

Correct Example

🐍Code Cell
1t = (10,)
2 
3print(t)
4 
5print(type(t))
Output
(10,)

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

🐍Code Cell
1t = (10, 20, 30, 40)
2 
3print(t[0])
4 
5print(t[2])
Output
10
30

Example - Negative Index

🐍Code Cell
1t = (10, 20, 30, 40)
2 
3print(t[-1])
4 
5print(t[-2])
Output
40
30

Tuple Slicing

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

Syntax

🐍Code Cell
1t[begin:end]
2 
3t[begin:end:step]
Output
No output captured.

Example 1 - Slice Operator

🐍Code Cell
1t = (10, 20, 30, 40, 50)
2 
3print(t[1:4])
Output
(20, 30, 40)

Example 2 - Complete Tuple

🐍Code Cell
1t = (10, 20, 30, 40, 50)
2 
3print(t[:])
Output
(10, 20, 30, 40, 50)

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

🐍Code Cell
1t = (10, 20, 30)
2 
3t[1] = 200
Output
TypeError: 'tuple' object does not support item assignment

Explanation

The tuple object is immutable.

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

Example 2 - Add a New Element

🐍Code Cell
1t = (10, 20, 30)
2 
3t.append(40)
Output
AttributeError: 'tuple' object has no attribute 'append'

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

🐍Code Cell
1t = (10, 20, 30)
2 
3del t[1]
Output
TypeError: 'tuple' object doesn't support item deletion

Deleting a Tuple

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

Example - Delete Complete Tuple

🐍Code Cell
1t = (10, 20, 30)
2 
3del t
4 
5print(t)
Output
NameError: name 't' is not defined

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

🐍Code Cell
1tuple3 = tuple1 + tuple2
Output
No output captured.

Example 1 - Join Two Tuples

🐍Code Cell
1t1 = (10, 20, 30)
2 
3t2 = (40, 50, 60)
4 
5t3 = t1 + t2
6 
7print(t3)
Output
(10, 20, 30, 40, 50, 60)

Example 2 - Join String Tuples

🐍Code Cell
1t1 = ("Python", "Java")
2 
3t2 = ("C", "C++")
4 
5print(t1 + t2)
Output
('Python', 'Java', 'C', 'C++')

Example 3 - Invalid Concatenation

🐍Code Cell
1t = (10, 20)
2 
3print(t + 30)
Output
TypeError: can only concatenate tuple (not "int") to tuple

Repetition Operator (*)

The * operator repeats the elements of a tuple.

A new tuple containing repeated elements is returned.

Syntax

🐍Code Cell
1new_tuple = tuple * number
Output
No output captured.

Example 1 - Repeat Tuple

🐍Code Cell
1t = (10, 20)
2 
3print(t * 3)
Output
(10, 20, 10, 20, 10, 20)

Example 2 - Repeat String Tuple

🐍Code Cell
1languages = ("Python", "Java")
2 
3print(languages * 2)
Output
('Python', 'Java', 'Python', 'Java')

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

🐍Code Cell
1len(tuple)
Output
No output captured.

Example 1 - Length of Tuple

🐍Code Cell
1t = (10, 20, 30, 40, 50)
2 
3print(len(t))
Output
5

Example 2 - Empty Tuple

🐍Code Cell
1t = ()
2 
3print(len(t))
Output
0

Example 3 - Heterogeneous Tuple

🐍Code Cell
1t = (10, "Python", 20.5, True)
2 
3print(len(t))
Output
4

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

🐍Code Cell
1tuple.count(element)
Output
No output captured.

Example 1 - Count Duplicate Elements

🐍Code Cell
1t = (10, 20, 10, 30, 10, 40)
2 
3print(t.count(10))
Output
3

Example 2 - Count String Elements

🐍Code Cell
1t = ("A", "B", "A", "C", "A")
2 
3print(t.count("A"))
Output
3

Example 3 - Element Not Present

🐍Code Cell
1t = (10, 20, 30)
2 
3print(t.count(100))
Output
0

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

🐍Code Cell
1tuple.index(element)
Output
No output captured.

Example 1 - Find Index

🐍Code Cell
1t = (10, 20, 30, 40)
2 
3print(t.index(30))
Output
2

Example 2 - Duplicate Elements

🐍Code Cell
1t = (10, 20, 10, 30, 10)
2 
3print(t.index(10))
Output
0

Explanation

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

Example 3 - Element Not Present

🐍Code Cell
1t = (10, 20, 30)
2 
3print(t.index(100))
Output
ValueError: tuple.index(x): x not in tuple

sorted() Function

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

The original tuple remains unchanged.

Syntax:

Syntax

🐍Code Cell
1sorted(tuple)
2 
3sorted(tuple, reverse=True)
Output
No output captured.

Example 1 - Ascending Order

🐍Code Cell
1t = (40, 10, 30, 20)
2 
3print(sorted(t))
Output
[10, 20, 30, 40]

Example 2 - Descending Order

🐍Code Cell
1t = (40, 10, 30, 20)
2 
3print(sorted(t, reverse=True))
Output
[40, 30, 20, 10]

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

🐍Code Cell
1min(tuple)
Output
No output captured.

Example

🐍Code Cell
1t = (40, 10, 30, 20)
2 
3print(min(t))
Output
10

max() Function

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

Syntax

🐍Code Cell
1max(tuple)
Output
No output captured.

Example

🐍Code Cell
1t = (40, 10, 30, 20)
2 
3print(max(t))
Output
40

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

🐍Code Cell
1tuple_name = value1, value2, value3
2 
3# or
4 
5tuple_name = (value1, value2, value3)
Output
No output captured.

Example 1 - Tuple Packing

🐍Code Cell
1t = 10, 20, 30, 40
2 
3print(t)
4 
5print(type(t))
Output
(10, 20, 30, 40)

Explanation

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

This process is called Tuple Packing.

Example 2 - Packing Different Data Types

🐍Code Cell
1student = (101, "Rahul", 85.5, True)
2 
3print(student)
Output
(101, 'Rahul', 85.5, True)

Example 3 - Packing Without Parentheses

🐍Code Cell
1data = 10, "Python", 20.5
2 
3print(data)
Output
(10, 'Python', 20.5)

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

🐍Code Cell
1variable1, variable2, variable3 = tuple_name
Output
No output captured.

Example 1 - Tuple Unpacking

🐍Code Cell
1t = (10, 20, 30)
2 
3a, b, c = t
4 
5print(a)
6print(b)
7print(c)
Output
10
20
30

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

🐍Code Cell
1student = (101, "Rahul", 85.5)
2 
3rollno, name, marks = student
4 
5print(rollno)
6print(name)
7print(marks)
Output
101
Rahul
85.5

Example 3 - Swap Two Variables

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

Program

🐍Code Cell
1a = 10
2b = 20
3 
4a, b = b, a
5 
6print("a =", a)
7print("b =", b)
Output
a = 20
b = 10

Example 4 - Invalid Unpacking

🐍Code Cell
1t = (10, 20, 30)
2 
3a, b = t
Output
ValueError: too many values to unpack (expected 2)

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

🐍Code Cell
1t = (10, 20, 30, 40, 50)
2 
3a, *b = t
4 
5print(a)
6print(b)
Output
10
[20, 30, 40, 50]

Example 2 - Collect Middle Elements

🐍Code Cell
1t = (10, 20, 30, 40, 50)
2 
3a, *b, c = t
4 
5print(a)
6print(b)
7print(c)
Output
10
[20, 30, 40]
50

Example 3 - Collect Initial Elements

🐍Code Cell
1t = (10, 20, 30, 40, 50)
2 
3*a, b = t
4 
5print(a)
6print(b)
Output
[10, 20, 30, 40]
50

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

🐍Code Cell
1(expression for variable in iterable)
Output
No output captured.

Example 1 - Generator Object

🐍Code Cell
1g = (x * x for x in range(1, 6))
2 
3print(g)
4 
5print(type(g))
Output
No output captured.

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

🐍Code Cell
1g = (x * x for x in range(1, 6))
2 
3t = tuple(g)
4 
5print(t)
6 
7print(type(t))
Output
(1, 4, 9, 16, 25)

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

🐍Code Cell
1g = (x for x in range(1, 6))
2 
3for value in g:
4 print(value)
Output
1
2
3
4
5

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