1

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.

4 Answers 4

16

There is no philosophical objection to your syntax, in fact, it's supported in Python 3.1:

>>> a, *b = range(10)
>>> a
0
>>> b
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> # Or even more flexibly:
>>> a, *b, c = range(10)
>>> a
0
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]
>>> c
9
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

Is this syntax supported in Python 2.6?
3

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]

2 Comments

is there a way to somehow figure out what the number of desired outputs is instead of supplying it as an input to the unpack function?
Without serious complication, no. You'd have to inspect the bytecode of the caller, which would be well past sanity. Reproducing the link you included above in another comment (where someone does just that): code.activestate.com/recipes/284742 . Doing something like this is similar to using macros in C to define new language constructs: very bad idea. Better to live with a few warts in the language you've chosen than to make up a language with only one programmer in the world who knows what it means.
3

Like this

results = foo()
x= results[0]
y= results[1:]

Or change your function to return a two-tuple

def foo():
    ....
    return someList[0], someList[1:]

1 Comment

this approach is taken more generally in the following: Recipe 284742: Finding out the number of values the caller is expecting code.activestate.com/recipes/284742
0

What you need to do is to return a list

e.g. return [ ... ]

You then receive the list and find its length e.g. abc=f(.....)

len(abc) would give you the number of elements in the list

for iiabc in abc: would allow you to access each of the elements

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.