Reputation: 41
I have the following list:
grid = [[2, 6, 8, 6, 9], [2, 5, 5, 5, 0], [1, 3, 8, 8, 7], [3, 2, 0, 6, 9], [2, 1, 4,5,8], [5, 6, 7, 4, 7]]
I used the fowling loop for traversing each element ->
for i in xrange(len(grid[i])):
for j in xrange(len(grid[j])):
print grid[i][j]
print "\n"
But it doesn't show the last row i.e [5,6,7,4,7]
So, which is the proper way to travers a 2D List in python?
Upvotes: 4
Views: 36571
Reputation: 1
If the number of columns are same in all the inner lists this should like==
li = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
for i in range(len(li)):
for j in range(len(li)):
print(li[i][j])
print()
And if you don't know no. of columns and in any situation, this would be helpful ==
for i in li:
for j in i:
print(j,end = " ")
print()
You can also use the following if rows and columns are different or the same:
li=[[1,2,3,4],[5,6,7],[8,9]]
for i in range(len(li)):
for j in range(len(li[i])):
print(li[i][j],end = " ")
print()
Upvotes: 0
Reputation: 162
Why not use while loop for traversing the 2D list
grid = [[2, 6, 8, 6, 9], [2, 5, 5, 5, 0], [1, 3, 8, 8, 7], [3, 2, 0, 6, 9], [2, 1, 4,5,8], [5, 6, 7, 4, 7]]
i = 0
while i < len(grid):
j = 0
while j < len(grid[0]):
print (grid[i][j], end=' ')
j += 1
print() #new line
i += 1
Upvotes: 0
Reputation: 171
Try following instead. You can do necessary operation instead of "print grid[i][j]"
for i in range(len(grid)):
for j in range(len(grid[i])):
print grid[i][j]
print '---'
Upvotes: 2
Reputation: 239473
The proper way to traverse a 2-D list is
for row in grid:
for item in row:
print item,
print
The for
loop in Python, will pick each items on every iteration. So, from grid
2-D list, on every iteration, 1-D lists are picked. And in the inner loop, individual elements in the 1-D lists are picked.
If you are using Python 3.x, please use the print
as a function, not as a statement, like this
for row in grid:
for item in row:
print(item, end = " ")
print()
Output
2 6 8 6 9
2 5 5 5 0
1 3 8 8 7
3 2 0 6 9
2 1 4 5 8
5 6 7 4 7
But, in case, if you want to change the element at a particular index, then you can do
for row_index, row in enumerate(grid):
for col_index, item in enumerate(row):
gird[row_index][col_index] = 1 # Whatever needs to be assigned.
Upvotes: 20
Reputation: 779
Why not:
for i in grid:
for j in i:
print("{}".format(j))
print("\n")
Upvotes: 0