Unpaking Tuple

Chris Rebert clp2 at rebertia.com
Sat Oct 6 06:27:52 EDT 2012


On Sat, Oct 6, 2012 at 3:09 AM, sajuptpm <sajuptpm at gmail.com> wrote:
> Hi,
>
> I am using python 2.6.
>
> 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).
>
> Note: Number of values in the tuple will change dynamically.

Then you arguably want a list, not a tuple.

But at any rate:
shortfall = 4 - len(your_tuple)
your_tuple += (None,) * shortfall # assuming None is a suitable default
a, b, c, d = your_tuple

If you also need to handle the "too many items" case, use slicing:
a, b, c, d = your_tuple[:4]

Cheers,
Chris



More information about the Python-list mailing list