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.
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 ?
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.
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 _.
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:
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,)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With