I have a list of lists:
JavaScript
x
2
1
a = [[1, 3, 4], [2, 5, 7]]
2
I want the output in the following format:
JavaScript
1
3
1
1 3 4
2
2 5 7
3
I have tried it the following way , but the outputs are not in the desired way:
JavaScript
1
4
1
for i in a:
2
for j in i:
3
print(j, sep=' ')
4
Outputs:
JavaScript
1
7
1
1
2
3
3
4
4
2
5
5
6
7
7
While changing the print call to use end
instead:
JavaScript
1
4
1
for i in a:
2
for j in i:
3
print(j, end = ' ')
4
Outputs:
JavaScript
1
2
1
1 3 4 2 5 7
2
Any ideas?
Advertisement
Answer
Iterate through every sub-list in your original list and unpack it in the print call with *
:
JavaScript
1
4
1
a = [[1, 3, 4], [2, 5, 7]]
2
for s in a:
3
print(*s)
4
The separation is by default set to ' '
so there’s no need to explicitly provide it. This prints:
JavaScript
1
3
1
1 3 4
2
2 5 7
3
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:
JavaScript
1
3
1
print(1, 3, 4) # for s = [1, 3, 4]
2
print(2, 5, 7) # for s = [2, 5, 7]
3