Question

I was wondering if this was possible:

def someFunction():
    return list(range(5))
first, rest = someFunction()

print(first) # 0
print(rest) # [1,2,3,4]

I know it could be accomplished with these 3 lines:

result = someFunction()
first = result[0]
rest = result[1:]
Was it helpful?

Solution

If you are using Python 3.x, it is possible to do this

first, *rest = someFunction()
print (first, rest)

Read more about it in this PEP

In Python 2, the best you can do is

result = someFunction()
first, rest = result[0], result[1:]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top