How to return an unpacked list in Python?
Question:
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.
Answers:
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,)
Note the accepted answer explains how to unpack some values when returning them as part of a tuple that includes some other values. What if you only want to return the unpacked list? Following up on a comment above:
def func():
list1 = [1,2,3]
return *list1
This gives SyntaxError: invalid syntax
.
The solution is to add parentheses (
and )
and a comma ,
after the return value, to tell Python that this unpacked list is part of a tuple:
def func():
list1 = [1,2,3]
return (*list1,)
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,)
Note the accepted answer explains how to unpack some values when returning them as part of a tuple that includes some other values. What if you only want to return the unpacked list? Following up on a comment above:
def func():
list1 = [1,2,3]
return *list1
This gives SyntaxError: invalid syntax
.
The solution is to add parentheses (
and )
and a comma ,
after the return value, to tell Python that this unpacked list is part of a tuple:
def func():
list1 = [1,2,3]
return (*list1,)