Nearby lessons
60 of 108Python - Tuple Data Structure
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.
Characteristics of Tuple
A Python tuple has the following characteristics:
- Insertion order is preserved.
- Duplicate objects are allowed.
- Heterogeneous objects are allowed.
- Tuple objects are immutable.
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
main.py
(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 |
main.py
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
main.py
(10, 20, 30, 40)
Creating an Empty Tuple
An empty tuple can be created using empty parentheses.
Example - Empty Tuple
main.py
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
main.py
10
Correct Example
main.py
(10,)
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
main.py
10 30
Example - Negative Index
main.py
40 30
Tuple Slicing
We can access multiple elements from a tuple using the slice operator.
Syntax
main.py
No output captured.
Example 1 - Slice Operator
main.py
(20, 30, 40)
Example 2 - Complete Tuple
main.py
(10, 20, 30, 40, 50)
Quick Summary
| Topic | Description |
|---|---|
| Tuple | Read-only version of List |
| Insertion Order | Preserved |
| Duplicate Objects | Allowed |
| Heterogeneous Objects | Allowed |
| Immutable | Yes |
| Representation | Parentheses () |
| Positive Index | Left to Right |
| Negative Index | Right to Left |
| Slice Operator | Access multiple elements |
Important Notes
- Tuple is exactly the same as a List except that it is immutable.
- If the data never changes, we should use a Tuple.
- Tuple preserves insertion order.
- Duplicate objects are allowed.
- Heterogeneous objects are allowed.
- Tuple supports both positive and negative indexing.
- Parentheses are optional but recommended while creating a tuple.
- A single-valued tuple must end with a comma (
,). - Tuple elements can be accessed using indexes or the slice operator.
- Since tuples are immutable, their elements cannot be modified after creation.
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
main.py
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
main.py
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
main.py
TypeError: 'tuple' object doesn't support item deletion
Important Notes
- Tuple elements cannot be modified.
- New elements cannot be added.
- Existing elements cannot be removed.
- The complete tuple object can be deleted using
del.
Deleting a Tuple
Although tuple elements cannot be deleted individually, the complete tuple object can be deleted.
Example - Delete Complete Tuple
main.py
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
main.py
No output captured.
Example 1 - Join Two Tuples
main.py
(10, 20, 30, 40, 50, 60)
Example 2 - Join String Tuples
main.py
('Python', 'Java', 'C', 'C++')Example 3 - Invalid Concatenation
main.py
TypeError: can only concatenate tuple (not "int") to tuple
Important Notes - (+)
- The
+operator creates a new tuple. - The original tuples remain unchanged.
- Only tuples can be concatenated.
Repetition Operator (*)
The * operator repeats the elements of a tuple.
A new tuple containing repeated elements is returned.
Syntax
main.py
No output captured.
Example 1 - Repeat Tuple
main.py
(10, 20, 10, 20, 10, 20)
Example 2 - Repeat String Tuple
main.py
('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. |
Comparison of Tuple Operators
| Operator | Purpose |
|---|---|
+ |
Concatenate two tuples. |
* |
Repeat tuple elements. |
Real World Usage
Tuples are commonly used in:
- Configuration data
- Coordinate values
- Fixed records
- Database results
- Function return values
Important Notes
- Tuple objects are immutable.
- Tuple elements cannot be modified after creation.
- The
+operator joins two tuples. - The
*operator repeats tuple elements. - Both operators return new tuple objects.
- The original tuples remain unchanged.
Quick Summary
| Topic | Description |
|---|---|
| Immutability | Tuple elements cannot be modified. |
| + | Concatenate tuples. |
| * | Repeat tuple elements. |
| del | Delete the complete tuple. |
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
main.py
No output captured.
Example 1 - Length of Tuple
main.py
5
Example 2 - Empty Tuple
main.py
0
Example 3 - Heterogeneous Tuple
main.py
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
main.py
No output captured.
Example 1 - Count Duplicate Elements
main.py
3
Example 2 - Count String Elements
main.py
3
Example 3 - Element Not Present
main.py
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
main.py
No output captured.
Example 1 - Find Index
main.py
2
Example 2 - Duplicate Elements
main.py
0
Explanation
If duplicate elements are available, the index of the first occurrence is returned.
Example 3 - Element Not Present
main.py
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
main.py
No output captured.
Example 1 - Ascending Order
main.py
[10, 20, 30, 40]
Example 2 - Descending Order
main.py
[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
main.py
No output captured.
Example
main.py
10
max() Function
The max() function returns the largest element from the tuple.
Syntax
main.py
No output captured.
Example
main.py
40
Comparison of Tuple Functions
| Function / Method | Purpose |
|---|---|
len() |
Returns the number of elements. |
count() |
Returns the number of occurrences. |
index() |
Returns the first occurrence index. |
sorted() |
Returns a sorted list. |
min() |
Returns the smallest element. |
max() |
Returns the largest element. |
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
Important Notes
len()returns the total number of elements.count()returns the number of occurrences of an element.index()returns the index of the first occurrence only.sorted()always returns a list.- The original tuple remains unchanged after using
sorted(). min()returns the smallest value.max()returns the largest value.
Quick Summary
| Function / Method | Description |
|---|---|
len() | Returns the number of elements. |
count() | Counts duplicate elements. |
index() | Returns the first occurrence index. |
sorted() | Returns a sorted list. |
min() | Returns the smallest value. |
max() | Returns the largest value. |
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
main.py
No output captured.
Example 1 - Tuple Packing
main.py
(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
main.py
(101, 'Rahul', 85.5, True)
Example 3 - Packing Without Parentheses
main.py
(10, 'Python', 20.5)
Important Notes - Tuple Packing
- Python automatically creates the tuple.
- Parentheses are optional.
- Multiple values are packed into a single tuple object.
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
main.py
No output captured.
Example 1 - Tuple Unpacking
main.py
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
main.py
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
main.py
a = 20 b = 10
Example 4 - Invalid Unpacking
main.py
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
main.py
10 [20, 30, 40, 50]
Example 2 - Collect Middle Elements
main.py
10 [20, 30, 40] 50
Example 3 - Collect Initial Elements
main.py
[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. |
Comparison Table
| Operation | Purpose |
|---|---|
| Tuple Packing | Store multiple values in a tuple. |
| Tuple Unpacking | Assign tuple values to variables. |
| * Operator | Collect remaining values during unpacking. |
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.
Important Notes
- Tuple packing combines multiple values into a tuple.
- Tuple unpacking separates tuple elements into variables.
- Parentheses are optional while packing.
- The number of variables and tuple elements should normally be equal.
- The
*operator collects remaining elements into a list. - Tuple unpacking is commonly used for variable swapping.
Quick Summary
| Topic | Description |
|---|---|
| Tuple Packing | Store multiple values into one tuple. |
| Tuple Unpacking | Assign tuple elements to variables. |
| * Operator | Collect remaining elements during unpacking. |
| Variable Swapping | Swap values without a temporary variable. |
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
main.py
No output captured.
Example 1 - Generator Object
main.py
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
main.py
(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
main.py
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.
Comparison of List and Tuple
| Feature | List | Tuple |
|---|---|---|
| Order | Preserved | Preserved |
| Duplicates | Allowed | Allowed |
| Heterogeneous Data | Allowed | Allowed |
| Mutable | Yes | No |
| Indexing | Supported | Supported |
| Slicing | Supported | Supported |
| Memory Usage | More | Less |
| Performance | Slower | Faster |
Important Notes
- Python does not support tuple comprehension.
- Using parentheses with a comprehension creates a generator object.
- The
tuple()function converts a generator into a tuple. - Generators produce values one by one.
- Generators consume less memory than lists.
- Lists are mutable, whereas tuples are immutable.
- Choose a list when data changes frequently.
- Choose a tuple when data remains fixed.
Complete Tuple Summary
| Topic | Description |
|---|---|
| Tuple | Immutable ordered collection. |
| Indexing | Positive and Negative indexing supported. |
| Slicing | Supported. |
| Packing | Store multiple values in one tuple. |
| Unpacking | Assign tuple values to variables. |
| Tuple Expression | Creates a Generator Object. |
| Generator | Produces values one by one. |
| Use Tuple | When data should not change. |