Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print list of lists in separate lines

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?

like image 295
skorada Avatar asked Aug 10 '16 11:08

skorada


People also ask

How do you print a list of elements in separate lines in Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by comma use sep=”\n” or sep=”, ” respectively.

How do I print a nested list from another line in Python?

We can use list comprehension and . join() operator. Inner print with a comma ensures that inner list's elements are printed in a single line. Outer print ensures that for the next inner list, it prints in next line.

Can you have a list of list of lists in Python?

Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.


2 Answers

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]
like image 136
Dimitris Fasarakis Hilliard Avatar answered Oct 16 '22 04:10

Dimitris Fasarakis Hilliard


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

like image 14
ailin Avatar answered Oct 16 '22 02:10

ailin