Print a nested list line by line - Python

Solution 1:

Use a simple for loop and " ".join() mapping each int in the nested list to a str with map().

Example:

>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
...     print(" ".join(map(str, xs)))
... 
1 2 3
4 5 6
7 8 9 10

The difference here is that we can support arbitrary lengths of inner lists.


The reason your example did not work as expected is because your inner loop is iterating over each element of the sub-list;

for r in A:  # r = [1, 2, 3]
    for t in r:  # t = 1 (on first iteration)
        print(t,)
    print

And print() by default prints new-line characters at the end unless you use: print(end="") I believe if you were using Python 2.x print t, would work. For example:

>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
...     for x in xs:
...             print x,
...     print
... 
1 2 3
4 5 6
7 8 9 10

But print(x,) would not work as you intended it; Python 2.x or 3.x

Solution 2:

for r in A:
    print '%d %d %d' % tuple(r)

Solution 3:

Method-1 :

We can use list comprehension and .join() operator.

>>> my_list = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]

>>> for item in my_list:
        print ' '.join(str(x) for x in item)

1 2 3
2 3 4
4 5 6

Method-2 :

>>> my_list = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]

>>> for item in my_list:
        for x in item:
            print x,
        print 

1 2 3
2 3 4
4 5 6

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.

Solution 4:

print without trailing comma will print a newline character.

for r in A:
    for t in r:
        print t,
    print