Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 866
dhokas Avatar asked Jun 09 '16 16:06

dhokas


People also ask

How to unpack a list in Python?

Unpacking assigns elements of the list to multiple variables. Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list. Did you find this tutorial helpful ?

What is sequence unpacking in Python and how to use it?

However, Python provides a better way to do this. It’s called sequence unpacking. Basically, you can assign elements of a list (and also a tuple) to multiple variables. For example: This statement assigns the first, second, and third elements of the colors list to the red, blue, and green variables.

How do you unpack a tuple in Python?

You can also unpack a nested tuple and list. If you want to expand the inner element, enclose the variable with () or []. By convention, unnecessary values may be assigned to underscores _ in Python. It does not have a grammatical special meaning, but is simply assigned to a variable named _.

How to unpack a unique element of an iterable in Python?

We can unpack a unique element of an iterable. For example, you’d come up with something like this: If we want to unpack all the values of an iterable to a single variable, we must set up a tuple, hence adding a simple comma will be enough:


1 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,)
like image 96
kennytm Avatar answered Sep 18 '22 02:09

kennytm