You have a tuple or list or any iterable of N items and you want to unpack them into N variables.
Let’s say you have a tuple which contains 3 elements.
In : data = (5, 10, 15)
And you want to assign 5 to a, 10 to b and 15 to c variables. One way of doing this is the following.
In : a = data In : b = data In : c = data
Here, we first access the element and then assign them into a variable. But you can see this is very verbose. A better way to perform this operation is the following.
In : a, b, c = data In : a Out: 5 In : b Out: 10 In : c Out: 15
In just One line unpack all the elements of the tuple. Only requirement for unpacking a tuple or any iterable is that the number of items on the right hand side should match with the number of variables on the left hand side. If they do not match then python will throw an error.
In : a, b, c, d = data Traceback (most recent call last): File "C:\Users\BHOLA\AppData\Local\Temp\ipykernel_8964\3571094354.py", line 1, in <module> a, b, c, d = data ValueError: not enough values to unpack (expected 4, got 3)
As I said before, you can unpack any iterable in python like this. Let’s unpack the characters of a string in this way.
In : a, b, c, d, e, f = 'python' In : a Out: 'p' In : b Out: 'y' In : c Out: 't' In : d Out: 'h' In : e Out: 'o' In : f Out: 'n'