Python unpack tuple into variables or arguments

Python examples to unpack an N-element tuple or sequence into a collection of N variables. Python example to unpack tuple into variables.

1. Python unpack tuple example

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.

1.1. Unpack example – 1

>>> data = (1, 2, 3)
>>> x, y, z = data
>>> x
1
>>> y
2
>>> z
3

1.2. Unpack example – 2

>>> 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

1.3. Unpack example – 3

>>> greeting = 'Hello'

>>> a, b, c, d, e = greeting

>>> a
'H'	
>>> b
'e'
>>> c
'o'

2. Possible error while unpacking

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 !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial