Tuple unpacking is the process of assigning the values of a tuple to a sequence of variables in a single statement. In other words, it allows you to extract individual elements from a tuple and assign them to separate variables.
Here's an example of tuple unpacking:
# create a tuple my_tuple = (1, 2, 3) # tuple unpacking a, b, c = my_tuple # print the variables print(a) # prints 1 print(b) # prints 2 print(c) # prints 3
In the above code, we create a tuple with three elements and then unpack it into three separate variables a, b, and c. The variables are assigned the values of the corresponding elements in the tuple in a single statement.
Tuple unpacking is a convenient way to assign multiple values at once and can be used in a variety of situations. For example, you might use it to assign the values returned by a function to separate variables, or to loop over the elements of a tuple and perform some operation on each one. It can also be used with variable-length tuples, where the number of variables on the left-hand side of the assignment matches the number of elements in the tuple.
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.