What is tuple unpacking in Python? Example
Python > Python Tuples > Python Tuples
306
Answer:
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.
This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.