Unpaking Tuple

Terry Reedy tjreedy at udel.edu
Sun Oct 7 16:03:20 EDT 2012


On 10/7/2012 1:58 PM, woooee wrote:
> On Oct 6, 3:09 am, sajuptpm <sajup... at gmail.com> wrote:
>> I need a way to make following code working without any ValueError .
>>
>>>>> a, b, c, d = (1,2,3,4)
>>>>> a, b, c, d = (1,2,3)

You cannot 'make' buggy code work -- except by changing it.
 >>> a, b, c, *d = (1,2,3)
 >>> d
[]

> Why is it necessary to unpack the tuple into arbitrary variables.

It is not necessary.

> a_tuple=(1,2,3)
> for v in a_tuple:
>      print v

This is often the right way to access any iterable.

> for ctr in range(len(a_tuple)):
>      print a_tuple[ctr]

This is seldom the right way. See the example below.

Unpacking is for when you have known-length iterables. For instance, 
enumerate produces pairs.

 >>> for i, v in enumerate('abc'):
   print('Item {} is {}.'.format(i, v))

Item 0 is a.
Item 1 is b.
Item 2 is c.

-- 
Terry Jan Reedy




More information about the Python-list mailing list