Ben
Ben

Reputation: 3

print a list in a square pattern [python]

I am trying to print a list, for example:

x = [ [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      [10, 11, 12]]

in a certain pattern like below:

1 2 3
4 5 6
7 8 9
10 11 12

but I couldn't figure it out.

In Java a simple nested for loop will do the job but not in Python. This is what I tried:

for i in range(0, 4):
    for j in range(0, 3):
        print(x[i][j])

But this just prints each number in a new line.

Upvotes: 0

Views: 909

Answers (2)

Tomerikoo
Tomerikoo

Reputation: 19414

The print function has some useful extra arguments. So:

You can either print each cell with an empty end and add a new line after each row:

for row in x:
    for cell in row:
        print(cell, end=" ")
    print()

Or, print each line with an empty sep:

for row in x:
    print(*row, sep=" ")

Or finally use the join method to combine all rows:

print('\n'.join(' '.join(str(cell) for cell in row) for row in x))

Upvotes: 1

Harshal Parekh
Harshal Parekh

Reputation: 6017

print() takes an optional parameter end:

for i in range(0, 4):
    for j in range(0, 3):
        print(x[i][j], end=" ")
    print()

Upvotes: 0

Related Questions