Skip to content

Python Tuple

Python Tuple

In Python, a tuple is an ordered and immutable collection of elements. It is defined by enclosing elements in parentheses () and separating them with commas. Tuples are similar to lists but with the key difference that once a tuple is created, its elements cannot be modified, added, or removed.

Example:

        
# Creating a tuple
fruits = ("apple", "orange", "banana")

# Accessing elements
first_fruit = fruits[0]  # Indexing starts at 0
second_fruit = fruits[1]
        
    

In the example above, fruits is a tuple containing three elements. The first fruit, "apple," is accessed using fruits[0], and the second fruit, "orange," is accessed using fruits[1]. Once a tuple is created, you cannot change its elements, making it immutable.

Tuples can be useful in situations where you want to represent a collection of items that should remain constant throughout the program's execution. They also offer better performance than lists for certain operations due to their immutability.