A tuple is a collection of items that are ordered and unchangeable. Tuples are similar to lists but with a key difference—they are immutable. This means once a tuple is created, its contents cannot be changed.

Syntax:

To create a tuple in Python, you simply place the items you want to include inside parentheses ( ), separated by commas. This can be done with any type of data—numbers, strings, or even other tuples. Here’s how you can create a simple tuple:

A tuple of items

my_tuple = ('apple', 'banana', 42, 3.14)

This tuple includes a mix of strings, an integer, and a float, demonstrating the versatility of tuple contents.

Creating and Accessing Tuples

Creating a tuple is as simple as placing the items you want to include in parentheses, separated by commas. To access items in a tuple, you use indexing just like you would with a list:

Accessing the second item in the tuple

print(my_tuple[1]) # Outputs 'banana'

Immutability of Tuples

The immutability of tuples is what sets them apart from lists. Once a tuple is created, you cannot add, remove, or change its elements. This might seem like a limitation, but it provides certain advantages, such as:

  • Safety: Since tuples cannot be changed, they are safe to pass around different parts of your program without worrying about accidental modifications.
  • Performance: Tuples can be faster than lists when iterating through data, making them a good choice for fixed data sets.

When to Use Tuples

Tuples are particularly useful when you want to ensure that a collection of items remains constant throughout the life of a program.

Here's one scenario where tuples are preferred:

  • Storing constant data: Such as days of the week, or directions on a compass.

Example of Tuple Operations

While you cannot modify tuples, you can perform other operations, such as counting elements or locating their positions:

# Count the number of times 'apple' appears in the tuple
print(my_tuple.count('apple'))  # Outputs 1

# Find the index of the element 'banana'
print(my_tuple.index('banana'))  # Outputs 1