Nearby lessons
65 of 159Python - Tuples
- 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
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 |
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
Creating an Empty Tuple
An empty tuple can be created using empty parentheses.
Example - Empty Tuple
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
Correct Example
Accessing Tuple Elements
Tuple elements can be accessed in two ways:
- Using Index
- Using Slice Operator
Python supports both positive and negative indexing.
Example - Positive Index
Example - Negative Index
Tuple Slicing
We can access multiple elements from a tuple using the slice operator.
Syntax
Example 1 - Slice Operator
Example 2 - Complete Tuple
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
Explanation
The tuple object is immutable.
Therefore, existing elements cannot be modified after the tuple is created.
Example 2 - Add a New Element
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
Deleting a Tuple
Although tuple elements cannot be deleted individually, the complete tuple object can be deleted.
Example - Delete Complete Tuple
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
Example 1 - Join Two Tuples
Example 2 - Join String Tuples
Example 3 - Invalid Concatenation
Repetition Operator (*)
The * operator repeats the elements of a tuple.
A new tuple containing repeated elements is returned.
Syntax
Example 1 - Repeat Tuple
Example 2 - Repeat String Tuple
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
Example 1 - Length of Tuple
Example 2 - Empty Tuple
Example 3 - Heterogeneous Tuple
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
Example 1 - Count Duplicate Elements
Example 2 - Count String Elements
Example 3 - Element Not Present
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
Example 1 - Find Index
Example 2 - Duplicate Elements
Explanation
If duplicate elements are available, the index of the first occurrence is returned.
Example 3 - Element Not Present
sorted() Function
The sorted() function sorts tuple elements and returns them as a new list.
The original tuple remains unchanged.
Syntax:
Syntax
Example 1 - Ascending Order
Example 2 - Descending Order
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
Example
max() Function
The max() function returns the largest element from the tuple.
Syntax
Example
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
Example 1 - Tuple Packing
Explanation
Python automatically packs all the given values into a tuple object.
This process is called Tuple Packing.
Example 2 - Packing Different Data Types
Example 3 - Packing Without Parentheses
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
Example 1 - Tuple Unpacking
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
Example 3 - Swap Two Variables
Tuple packing and unpacking are commonly used to swap two variables without using a temporary variable.
Program
Example 4 - Invalid Unpacking
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
Example 2 - Collect Middle Elements
Example 3 - Collect Initial Elements
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
Example 1 - Generator Object
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
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
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.
- 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