Python – return variable outputs in Python function

python

I have a function that returns a list. When I know the number of elements in the list I can do something like:

x,y,z=foo()

however, the number of elements in the list can vary. I would like to do something like

x,y*=foo()

where x would contain the first element in the returned list and y* would contain the remainder of however many elements there are left. Obviously , this syntax is not supported in Python. Is there a philosophical reason for this? Am I thinking about this the wrong way?

thanks in advance.

Best Answer

A slightly generalized approach:

>>> def unpack(seq, count):
...   return seq[:count] + [seq[count:]]
>>> a, b = unpack([1, 2, 3], 1)
>>> a
1
>>> b
[2, 3]
>>> a, b = unpack([1, 2], 1)
>>> a
1
>>> b
[2]
>>> a, b = unpack([1], 1)
>>> a
1
>>> b
[]
>>> a, b = unpack([], 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
>>> a, b, c, d = unpack(range(10), 3)
>>> a
0
>>> b
1
>>> c
2
>>> d
[3, 4, 5, 6, 7, 8, 9]