Python: unpack to unknown number of variables?

Nope picture Nope · Jan 11, 2009 · Viewed 12.7k times · Source

How could I unpack a tuple of unknown to, say, a list?

I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need?

Thanks for your help :)

Answer

Evan Fosmark picture Evan Fosmark · Jan 11, 2009

You can use the asterisk to unpack a variable length. For instance:

foo, bar, *other = funct()

This should put the first item into foo, the second into bar, and all the rest into other.

Update: I forgot to mention that this is Python 3.0 compatible only.