Python

Tuples

A tuple in Python is a immutable sequence type, similar to a list. However, unlike lists, tuples cannot be modified once created. This means that you cannot add, remove, or change the values of elements in a tuple.

Tuples are often used to store related data that should not be modified. For example, you might use a tuple to store a person’s name, age, and address. Tuples are also often used to return multiple values from a function.

Tuple Creation

To create a tuple, you can use parentheses and separate the values with commas. For example:

my_tuple = (1, 2, 3)

You can also create a tuple without using parentheses by using a comma to separate the values. For example:

my_tuple = 1, 2, 3
Tuple Indexing

You can access the values in a tuple using indexing, just like with a list. For example:

print(my_tuple[0])  # Outputs 1
Tuple Slicing

You can also use slicing to access a range of values in a tuple. For example:

print(my_tuple[1:3])  # Outputs (2, 3)
Tuple Unpacking

You can iterate over the values in a tuple using a for loop, just like with a list. For example:

for value in my_tuple:
    print(value)  # Outputs 1, 2, 3

You can also use built-in functions like len(), min(), and max() with tuples. For example:

print(len(my_tuple))  # Outputs 3
print(min(my_tuple))  # Outputs 1
print(max(my_tuple))  # Outputs 3

Tuples are a useful data type to store immutable data and can be used in a variety of situations where you need to store and work with data that will not change, like days of the week.