How to return an unpacked list in Python?
Asked Answered
H

2

14

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.

Hightest answered 9/6, 2016 at 16:57 Comment(0)
A
21

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,)
Acerbic answered 9/6, 2016 at 17:1 Comment(2)
def func(): list1 = [1,2,3] return *list1 is there's a way to achieve this using print(*list1) is possible but I would like to return in formatted string or just normallyNaturalism
@AzharUddinSheikh - see my answer below.Luthern
L
10

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,)
Luthern answered 4/11, 2022 at 14:33 Comment(1)
Nice workaround!Gamopetalous

© 2022 - 2024 — McMap. All rights reserved.