Python Tuples

A tuple in Python is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning their elements cannot be changed after the tuple is created. Tuples can contain elements of any data type, and they are commonly used when you want to store a collection of items that should not be modified.

What is a Tuple?

A tuple in Python is defined by enclosing elements in parentheses (), separated by commas. Once a tuple is created, its elements cannot be changed, added, or removed.

Syntax


# Syntax for creating a tuple
my_tuple = (1, 2, 3, 4, 5)  # A tuple of integers
string_tuple = ("apple", "banana", "cherry")  # A tuple of strings
mixed_tuple = (1, "apple", 3.14, True)  # A tuple with mixed data types
                

Explanation:

Example: Accessing Tuple Elements


my_tuple = (10, 20, 30, 40)

# Accessing the first element
print("First element:", my_tuple[0])

# Accessing the third element
print("Third element:", my_tuple[2])
                

Output

First element: 10 Third element: 30

In this example, we created a tuple my_tuple and accessed the first and third elements. The output shows the values 10 and 30.

Example: Tuple with Multiple Data Types


# Example: A tuple with different data types
mixed_tuple = (1, "apple", 3.14, True)
print(mixed_tuple)
                

Output

(1, 'apple', 3.14, True)

This example demonstrates creating a tuple with multiple data types: an integer, string, float, and boolean. The output shows the tuple with all its elements.

Best Practices for Using Tuples