Python tuples are a basic data structure that is used to store a collection of items. Unlike lists, which are mutable (meaning they can be changed), tuples are immutable, which means that once they are created, the items in them cannot be changed.
Tuples are defined using parentheses, with each item separated by a comma. For example, the following creates a tuple with three items:
my_tuple = (1, "hello", 3.14)
You can access the items in a tuple using indexing, just like you would with a list. For example, the following will return the second item in the tuple (in this case, “hello”):
print(my_tuple[1])
You can also use negative indexing to access items from the end of the tuple. For example, the following will return the last item in the tuple (in this case, 3.14):
print(my_tuple[-1])
Tuples also support slicing, which allows you to extract a range of items from the tuple. For example, the following will return a new tuple containing the first and second items from the original tuple:
new_tuple = my_tuple[0:2]
One of the key benefits of using tuples is that they are very efficient in terms of memory usage. Since they are immutable, Python can use a more compact representation for them, which can be especially useful when working with large collections of data.
Another benefit of tuples is that they can be used as keys in dictionaries. Since lists are mutable, they cannot be used as keys in dictionaries, but tuples can be used because they are immutable.
In addition, tuples are often used to return multiple values from a function. For example, a function that calculates the area and perimeter of a rectangle could return the values as a tuple, like this:
def rectangle_info(length, width):
area = length * width
perimeter = 2 * (length + width)
return (area, perimeter)
info = rectangle_info(3, 4)
print("Area:", info[0])
print("Perimeter:", info[1])
In conclusion, Python tuples are a powerful and efficient data structure that are well-suited for storing collections of items that do not need to be changed. They are also useful for returning multiple values from a function, and as keys in dictionaries.