How to traverse a 2D List in python

list, python, python-2.7

Solution

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.

Problem

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?

Original source