f-string syntax for unpacking a list with brace suppression f-string syntax for unpacking a list with brace suppression python-3.x python-3.x

f-string syntax for unpacking a list with brace suppression


Since any valid Python expression is allowed inside the braces in an f-string, you can simply use str.join() to produce the result you want:

>>> a = [1, 'a', 3, 'b']>>> f'unpack a list: {" ".join(str(x) for x in a)}''unpack a list: 1 a 3 b'

You could of course also write a helper function, if your real-world use case makes the above more verbose than you'd like:

def unpack(s):    return " ".join(map(str, s))  # map(), just for kicks

>>> f'unpack a list: {unpack(a)}''unpack a list: 1 a 3 b'


Just add a coma after the unpacked list.

a = [1, 2, 3]print(f"Unpacked list: {*a,}")

There is a longer explanation to this syntax in this thread.


Simple Python is probably more clear:

>>>  'unpack a list: ' + ' '.join(str(x) for x in a)'unpack a list: 1 a 3 b'

With slicing:

>>> 'unpack a list: ' + ' '.join([str(x) for x in a][1:3])'unpack a list: a 3'