5.2. Python Data Structures: Tuples
One of the fundamental data structures in Python is the tuple. Tuples are sequences, just like lists. The difference between the two is that tuples cannot be changed, unlike lists. Tuples are used to display things that shouldn't change, like days of the week or dates on a calendar. In this section, we'll learn more about tuples, how to create, access, modify, and manipulate them using various built-in methods in Python.
Creating Tuples
A tuple is created by enclosing all items (elements) inside parentheses (), separated by commas. The tuple can have any number of items and they can be of different types (integer, float, list, string, etc.).
# Creating a tuple tuple1 = ('apple', 'banana', 'cherry')
A tuple can also be created without using parentheses. This is known as tuple packing.
# tuple packing tupla2 = 'apple', 'banana', 'cherry'
A tuple with a single item is called a singleton tuple and to write it, you need to include a comma, even if there is only one value.
# singleton tuple tuple3 = ('apple',)
Accessing Elements of Tuples
Elements of a tuple are accessed using square brackets [] and the index of the desired element. Indexes start at 0 for the first element.
# Accessing elements of a tuple print(tuple1[0]) # Output: 'apple'
We can also use the negative index to access the elements of the tuple from the end. -1 refers to the last item, -2 refers to the next-to-last item, and so on.
# Accessing elements of a tuple with negative indices print(tuple1[-1]) # Output: 'cherry'
Altering and Deleting Tuples
Tuples are immutable, which means that we cannot alter or modify a tuple once it has been created. Attempting to change an element of the tuple will result in an error.
# Trying to change a tuple tuple1[0] = 'pear' # Output: TypeError
Since tuples are immutable, we cannot remove or delete an item from a tuple. However, it is possible to delete the entire tuple using the del command.
# Deleting a tuple del tuple1
Operations on Tuples
We can perform various operations on tuples such as concatenation (+), repetition (*), indexing ([]), slicing ([:]) and so on. In addition, Python provides a number of built-in functions such as len(), max(), min() and tuple() to make it easier to manipulate tuples.
In conclusion, tuples are an important part of Python programming and provide a means of grouping data that should not change. They are especially useful for data that is inherently immutable, such as dates, times, and unique identifiers.