Posts: 17
Threads: 12
Joined: Jul 2019
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.
Posts: 6,808
Threads: 20
Joined: Feb 2020
An asterisk before a container unpacks the container. *[a, b, c] becomes a, b, c
Posts: 1,583
Threads: 3
Joined: Mar 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
Posts: 1,950
Threads: 8
Joined: Jun 2018
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
|