Print list of lists in separate lines
Solution 1
Iterate through every sub-list in your original list and unpack it in the print call with *
:
a = [[1, 3, 4], [2, 5, 7]]
for s in a:
print(*s)
The separation is by default set to ' '
so there's no need to explicitly provide it. This prints:
1 3 4
2 5 7
In your approach you were iterating for every element in every sub-list and printing that individually. By using print(*s)
you unpack the list inside the print call, this essentially translates to:
print(1, 3, 4) # for s = [1, 3, 4]
print(2, 5, 7) # for s = [2, 5, 7]
Solution 2
oneliner:
print('\n'.join(' '.join(map(str,sl)) for sl in l))
explanation:
you can convert list
into str
by using join function:
l = ['1','2','3']
' '.join(l) # will give you a next string: '1 2 3'
'.'.join(l) # and it will give you '1.2.3'
so, if you want linebreaks you should use new line symbol.
But join accepts only list of strings. For converting list of things to list of strings, you can apply str
function for each item in list:
l = [1,2,3]
' '.join(map(str, l)) # will return string '1 2 3'
And we apply this construction for each sublist sl
in list l
Solution 3
You can do this:
>>> lst = [[1, 3, 4], [2, 5, 7]]
>>> for sublst in lst:
... for item in sublst:
... print item, # note the ending ','
... print # print a newline
...
1 3 4
2 5 7
Solution 4
lst = [[1, 3, 4], [2, 5, 7]]
def f(lst ):
yield from lst
for x in f(lst):
print(*x)
using "yield from"...
Produces Output
1 3 4
2 5 7
[Program finished]
Solution 5
a = [[1, 3, 4], [2, 5, 7]]
for i in a:
for j in i:
print(j, end = ' ')
print('',sep='\n')
output:
1 3 4
2 5 7
skorada
Updated on December 16, 2021Comments
-
skorada over 2 years
I have a list of lists:
a = [[1, 3, 4], [2, 5, 7]]
I want the output in the following format:
1 3 4 2 5 7
I have tried it the following way , but the outputs are not in the desired way:
for i in a: for j in i: print(j, sep=' ')
Outputs:
1 3 4 2 5 7
While changing the print call to use
end
instead:for i in a: for j in i: print(j, end = ' ')
Outputs:
1 3 4 2 5 7
Any ideas?
-
Amit Verma almost 4 yearsPls add some description to your answer and explain how it works and solves the problem.
-
DuDa about 3 yearsPlease read the question again since this answer does not solve the issue of the question.
-
Tomerikoo almost 3 yearsYour last print is quite confusing for no reason.
print('',sep='\n') == print()
... -
arnavlohe15 about 2 yearsHow would you print the transpose of this without libraries?