简体   繁体   中英

How to return an unpacked list in Python?

I'm trying to do something like this in python:

def f():
    b = ['c', 8]
    return 1, 2, b*, 3

Where I want f to return the tuple (1, 2, 'c', 8, 3) . I found a way to do this using itertools followed by tuple , but this is not very nice, and I was wondering whether there exists an elegant way to do this.

The unpacking operator * appears before the b , not after it.

return (1, 2, *b, 3)
#      ^      ^^   ^

However, this will only work on Python 3.5+ ( PEP 448 ), and also you need to add parenthesis to prevent SyntaxError. In the older versions, use + to concatenate the tuples:

return (1, 2) + tuple(b) + (3,)

You don't need the tuple call if b is already a tuple instead of a list:

def f():
    b = ('c', 8)
    return (1, 2) + b + (3,)

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