Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack 1 variable, rest to a list

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:]
like image 377
Bartlomiej Lewandowski Avatar asked Jan 25 '14 18:01

Bartlomiej Lewandowski


People also ask

Can list be unpacked?

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 [] .

How do you unpack a variable in Python?

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, * .


1 Answers

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:]
like image 115
thefourtheye Avatar answered Oct 12 '22 13:10

thefourtheye