简体   繁体   中英

Unpacking function return values to single value and tuple, in one line

I often use library functions which return many values in a tuple:

def f():
    return "a", "b", "c", "d"

Is it possible to (in a single step) unpack the first value while keeping the rest in a tuple? Ie do this:

ret = f()
a, b_to_d = ret[0], ret[1:]

but in one line.

Yes, using the * syntax below:

>>> def f():
...  return 1,2,3,4
...
>>> a,*b = f()
>>> a
1
>>> b
[2, 3, 4]
>>> a,*b,c = f()  # * can be used in other positions, too
>>> a,b,c
(1, [2, 3], 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM