How to return an unpacked list in Python?

dhokas picture dhokas · Jun 9, 2016 · Viewed 9.6k times · Source

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.

Answer

kennytm picture kennytm · Jun 9, 2016

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,)