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:]
Unpack a nested tuple and list. You can also unpack a nested tuple or list. If you want to expand the inner element, enclose the variable with () or [] .
Introduction. Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .
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:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With