Tuples

Tuples

In Python, a tuple is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning their elements cannot be modified once they are defined. This section covers the basics of tuples and common tuple operations.

1. Creating Tuples

You can create a tuple by enclosing elements in parentheses () and separating them with commas.

fruits = ("apple", "banana", "cherry")

A tuple can contain elements of different data types, just like lists.

mixed_tuple = (1, "apple", 3.14, True)

2. Accessing Tuple Elements

You can access elements in a tuple by their index, similar to lists. Indexing starts from 0 for the first element.

fruits = ("apple", "banana", "cherry")
first_fruit = fruits[0]  # Access the first element
second_fruit = fruits[1]  # Access the second element

Negative indexing can be used to access elements from the end of the tuple.

last_fruit = fruits[-1]  # Access the last element (cherry)

3. Slicing Tuples

You can slice a tuple to access a portion of its elements by specifying a range of indices.

numbers = (1, 2, 3, 4, 5)
subtuple = numbers[1:4]  # Slice from index 1 (inclusive) to 4 (exclusive)
# subtuple will be (2, 3, 4)

You can omit the starting or ending index to slice from the beginning or to the end of the tuple, respectively.

first_three = numbers[:3]  # Slice from the start to index 3
last_two = numbers[3:]  # Slice from index 3 to the end

4. Modifying Tuples

Tuples are immutable, so you cannot change their elements once they are defined. If you need to modify a tuple, you must create a new one with the desired elements.

numbers = (1, 2, 3)
new_numbers = numbers + (4, 5)  # Create a new tuple with additional elements

5. Tuple Operations

Tuples support various operations, such as concatenation and repetition.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2  # Concatenation
repeated = tuple1 * 3  # Repetition

6. Tuple Packing and Unpacking

Tuple packing is the process of creating a tuple with multiple elements, while tuple unpacking is the process of extracting elements from a tuple into separate variables.

coordinates = (3, 4)
x, y = coordinates  # Unpack the tuple into variables x and y

Tuple packing and unpacking are often used in functions that return multiple values.

Tuples are often used in situations where data should remain constant or should not be accidentally modified. They provide a structured way to represent and work with collections of data.