python: Unpacking a Tuple into Separate Variables
In the article we will look forward to unpacking a tuple or sequence into separate variables.
Suppose you have an (n)-element tuple or sequence that you would like to unpack into a collection of n variables.
Any sequence or tuple can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence. For example:
>>> p = (4, 5) >>> x, y = p >>> x 4 >>> y 5 >>> >>> data = [ 'APPL', 50, 91.1, (2012, 12, 21) ] >>> name, shares, price, date = data >>> name 'APPL' >>> date (2012, 12, 21) >>> name, shares, price, (year, mon, day) = data >>> name 'APPL' >>> year 2012 >>> mon 12 >>> day 21 >>>
If there is a mismatch in the number of elements, you’ll get an error. For example:
>>> 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 >>>
Unpacking works with any object that is iterable, not just tuples or lists. This includes strings, files, iterators, and generators. For example:
>>> s = 'Hello' >>> a, b, c, d, e = s >>> a 'H' >>> b 'e' >>> e 'o' >>>
When unpacking, you may sometimes want to discard certain values. Python has no special syntax for this, but you can often just pick a throwaway variable name for it. For example:
>>> data = [ 'APPL', 50, 91.1, (2012, 12, 21) ] >>> _, shares, price, _ = data >>> shares 50 >>> price 91.1 >>>
Unpacking a Tuple or Sequence into Separate Variables of Arbitrary Length.
You need to unpack n elements from a tuple or sequence, but the iterable may be longer than n elements, causing a “too many values to unpack” exception.
The solution to this is to use python star expressions. Suppose you have a sequence of 4 entries in it and you are only interested in first two entries. You might me thinking of creating four variable or creating two variable and two throw away variable and use the first two. However, this becomes an issue if you have say 30 entries in the sequence.
An star expression makes it easy. For example.
>>> record = ('Manjulam', 'firstname.lastname@example.org', '12121212', '13131313') >>> name, email, *phone_numbers = record >>> name 'Manjulam' >>> email 'email@example.com' >>> phone_numbers ['12121212', '13131313'] >>>
it is worth noting that star expression variable will always be a list. Star expression variable can be at the beginning or in the middle.
That’s all for now for unpacking a tuple or sequence into separate variables.