Tuples in Python
Tuples are a fundamental data type in Python, similar to lists. However, they are immutable, which means that they cannot be modified once they are created. In this article, we will cover everything you need to know about tuples in Python, including how to create them, access their elements, and perform operations on them.
Creating Tuples in Python
In Python, you can create a tuple by enclosing a sequence of values in parentheses. Here are some examples:
In the above examples, we are creating three different tuples, each containing a different combination of data types.
Accessing Elements in a Tuple
You can access individual elements in a tuple using their indices, just like in a list. Here is an example:
In the above example, we are accessing the first and second elements of the tuple using their indices.
Tuples are Immutable
As mentioned earlier, tuples are immutable, which means that they cannot be modified once they are created. Here is an example:
In the above example, we are attempting to modify the second element of the tuple, which raises a TypeError because tuples are immutable.
Tuple Packing and Unpacking
Tuple packing is the process of combining values into a tuple. Tuple unpacking is the opposite process of extracting values from a tuple. Here are some examples:
In the above examples, we are packing three values into a tuple and then unpacking them into separate variables.
Tuple Operations in Python
Python provides several built-in functions for performing operations on tuples. Here are some of the most commonly used ones:
In the above examples, we are finding the length of a tuple using the len() function, concatenating two tuples using the + operator, and repeating a tuple using the * operator.
In this article, we discussed everything you need to know about tuples in Python. We covered how to create tuples, access their elements, perform tuple packing and unpacking, and perform operations on them.