Python Forum

Full Version: Taking brackets out of list in print statement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I take brackets out of multiple lists in a print statement. Say I have the following lists of numbers:

j = [2,5]
k = [4,6]
e = [7,8]
r = [9,1]
How would I print "The numbers you have selected are 2,5,4,6,7,8,9,1"? I want to print the numbers from all the lists without the brackets in between.
An asterisk before a container unpacks the container. *[a, b, c] becomes a, b, c
Couple of methods:

import itertools
j = [2,5]
k = [4,6]
e = [7,8]
r = [9,1]

#Nested list comprehension
items = [str(x) for sublist in [j, k, e, r] for x in sublist]
print(f"The numbers you have selected are {','.join(items)}")

#chain iterable
items2 = ",".join(map(str,itertools.chain(j,k,e,r)))
print(f"The numbers you have selected are {items2}")
Output:
The numbers you have selected are 2,5,4,6,7,8,9,1 The numbers you have selected are 2,5,4,6,7,8,9,1
Another way without any datatype conversion:

j = [2,5] 
k = [4,6] 
e = [7,8] 
r = [9,1]

print('The numbers you have selected are', end=' ')
print(*j, *k, *e, *r, sep=', ')
If one will run this file output will be:

Output:
The numbers you have selected are 2, 5, 4, 6, 7, 8, 9, 1
If order is not important and you want things more 'human-readable' then you can sort them as well:

print('The numbers you have selected are', end=' ')
print(*sorted([*j, *k, *e, *r]), sep=', ')
This will output:

Output:
The numbers you have selected are 1, 2, 4, 5, 6, 7, 8, 9