dhokas dhokas - 5 months ago 10
Python Question

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.

Answer

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