17

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?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Nope
  • 34,682
  • 42
  • 94
  • 119

3 Answers3

37

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.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Evan Fosmark
  • 98,895
  • 36
  • 105
  • 117
10

Unpack the tuple to a list?

l = list(t)
PEZ
  • 16,821
  • 7
  • 45
  • 66
  • But I'm curious as to why you want to do it. =) – PEZ Jan 10 '09 at 23:28
  • PEZ, I'm making a script to handle a bunch of plotting using the numpy function 'loadtxt". The number of data columns are known only at run time so I can't make var names. – Nope Jan 11 '09 at 03:56
  • 1
    Yeah, but if you have the data in a tuple you can often still work with it like you can with a list. t[1] will give you the same data as l[1] without the "unpack". Of course, if you're modifying the data "in place" would you need a list. – PEZ Jan 11 '09 at 10:46
  • @PEZ - realize I'm bumping, but this can be useful e.g. for unpacking arguments or complex parsing. e.g.: (opt1, opt2,) = tuple(argument.split('-')[2:]) - this code won't actually work because opt1 and 2 are not optional but required to exist. Not the best use case in the world, but my google search on the subject brought me here. – smaudet May 04 '18 at 05:42
4

Do you mean you want to create variables on the fly? How will your program know how to reference them, if they're dynamically created?

Tuples have lengths, just like lists. It's perfectly permissable to do something like:

total_columns = len(the_tuple)

You can also convert a tuple to a list, though there's no benefit to doing so unless you want to start modifying the results. (Tuples can't be modified; lists can.) But, anyway, converting a tuple to a list is trivial:

my_list = list(the_tuple)

There are ways to create variables on the fly (e.g., with eval), but again, how would you know how to refer to them?

I think you should clarify exactly what you're trying to do here.

Brian Clapper
  • 25,705
  • 7
  • 65
  • 65