Print a nested list line by line - Python

quarters picture quarters · May 29, 2015 · Viewed 25.1k times · Source

A = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]

I am trying my best to print A of the form:

1 2 3
2 3 4
4 5 6

That is in different lines, but I am unable to do so without all the elements in different lines. This is my code so far:

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

This is my output:

1
2
3
2
3
4
4
5
6

It seems really simple, and I think a minor change would do it. Thanks!

Answer

James Mills picture James Mills · May 29, 2015

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