Python examples to unpack an N-element tuple or sequence into a collection of N variables.
Unpack tuple examples
Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence.
>>> data = (1, 2, 3) >>> x, y, z = data >>> x 1 >>> y 2 >>> z 3
>>> data = [ 'Lokesh', 37, 73.5, (1981, 1, 1) ] >>> name, age, weight, dob = data >>> name 'Lokesh' >>> dob (1981, 1, 1) # Another Variation >>> name, age, weight, (year, mon, day) = data >>> name 'Lokesh' >>> year 1981 >>> mon 1 >>> day 1
>>> greeting = 'Hello' >>> a, b, c, d, e = greeting >>> a 'H' >>> b 'e' >>> c 'o'
If there is a mismatch in the number of elements, you’ll get an error.
>>> p = (4, 5) >>> x, y, z = p Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 2 values to unpack
Happy Learning !!