Tuples

A tuple is an immutable ordered collection of elements in Python. Unlike lists, which are mutable, tuples cannot be modified once they are created. The elements in a tuple can be of different data types, and they are ordered and accessible by index.

Tuples are defined by enclosing the elements within parentheses, with each element separated by a comma. For example:

>>> my_tuple = (1, 2, 3, "hello", True)
>>> type(my_tuple)
<class 'tuple'>

Accessing elements in a tuple is similar to accessing elements in a list, using the square brackets and the index of the element. However, once a tuple is created, its elements cannot be modified, only accessed.

>>> my_tuple = (1, 2, 3, "hello", True)
>>> my_tuple[0]
1
>>> my_tuple[2]
3
>>> my_tuple[-1]
True

Tuples can also be sliced, similar to lists, to access a range of elements within the tuple.

>>> my_tuple = (1, 2, 3, "hello", True)
>>> my_tuple[1:3]
(2, 3)
>>> my_tuple[2:]
(3, 'hello', True)
>>> my_tuple[:3]
(1, 2, 3)

Tuples are commonly used to return multiple values from a function, as opposed to returning a single value or a list. This is because tuples allow for the values to be returned as an ordered, immutable collection, rather than a mutable list that can be changed outside of the function.

>>> def get_name_age():
    return ("John", 30)

>>> name, age = get_name_age()
>>> print(name)
John
>>> print(age)
30

Tuples can also be used as key-value pairs in dictionaries, where the tuple acts as the key and the value can be accessed through the key.

>>> my_dict = {("John", 30): "Developer", ("Jane", 25): "Designer"}
>>> my_dict[("John", 30)]
'Developer'

In conclusion, tuples are an essential part of Python, providing an ordered, immutable collection of elements that can be accessed by index. They can be used for a variety of purposes, including returning multiple values from a function, as key-value pairs in dictionaries, and for grouping elements together in a compact manner.