close menu
Tuples--Immutable-Sequences-in-Python Tuples Immutable Sequences in Python

Tuples Immutable Sequences in Python

13 February 2025

 Tuples  Immutable Sequences in Python


Tuples: Immutable Sequences in Python

A tuple is an immutable sequence in Python, meaning its elements cannot be modified after creation. Tuples are commonly used when data integrity is crucial, such as storing fixed collections of values.

Key Characteristics of Tuples:
- Ordered : Elements maintain their original sequence.
- Immutable : Once created, elements cannot be changed, added, or removed.
- Heterogneous : Can store different data types, including numbers, strings, and other collections.
- Faster than lists : Since tuples are immutable, they provide better performance in iterations.

Creating a Tuple

A tuple is defined using parentheses () and elements separated by commas:
# Example of a tuple
my_tuple = (1, "Python", 3.14)
print(my_tuple)  # Output: (1, 'Python', 3.14)

For a single-element tuple, include a trailing comma:
single_element_tuple = (42,)  # Correct
not_a_tuple = (42)  # Interpreted as an integer

Tuple Operations
Although tuples are immutable, they support:
- Indexing : Accessing elements via their position.
- Slicing : Extracting sub-tuples.
- Concatenation : Combining multiple tuples.
- Membership Testing : Checking for an element's presence.

Example:
t1 = (1, 2, 3)
t2 = (4, 5, 6)

# Concatenation
t3 = t1 + t2  
print(t3)  # Output: (1, 2, 3, 4, 5, 6)

# Slicing
print(t3[1:4])  # Output: (2, 3, 4)

# Membership
print(2 in t1)  # Output: True

Use Cases of Tuples
- Returning multiple values from functions 
- Storing configuration settings
- Using as dictionary keys(since they are hashable)
- Ensuring data integrity

Tuple vs. List: Key Differences

Feature: Mutability    
Tuple: Immutable
List: Mutable
    
Feature: Performance    
Tuple: Faster
List: Slightly slower
    
Feature: Memory Usage    
Tuple: Less
List: More

Feature: Use Case
Tuple: Fixed Data
List: Dynamic Data 
        
Tuples are a powerful and efficient data structure, making them a preferred choice in scenarios where immutability is required.

Whatsapp logo