Reputation: 3
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
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
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