Python Forum
Taking brackets out of list in print statement - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Taking brackets out of list in print statement (/thread-25830.html)



Taking brackets out of list in print statement - pythonprogrammer - Apr-13-2020

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.


RE: Taking brackets out of list in print statement - deanhystad - Apr-13-2020

An asterisk before a container unpacks the container. *[a, b, c] becomes a, b, c


RE: Taking brackets out of list in print statement - bowlofred - Apr-13-2020

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



RE: Taking brackets out of list in print statement - perfringo - Apr-13-2020

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