[Tutor] Accessing Values of specific column in a 2D list or array

Eric Abrahamsen eric at abrahamsen.com
Sun Sep 2 12:37:43 CEST 2007


> grid = [[1,1,2,7,6,9],\
>           [,9,1,1,1,9,1],\
>           [8,1,2,0,0,4],\
>           [1,4,1,1,8,5]]
>
> how can i access to all the elements of the list from column no. 5.
>
> output should be like [6,9,0,8]...

Your basic tool is sub-indexing: you can reach items in the sub-lists  
by using grid[x][x].

So use a 'for' loop to get sub-index four of every item in grid. The  
most compact way is with a list comprehension:

grid = [[1,1,2,7,6,9],[9,1,1,1,9,1],[8,1,2,0,0,4],[1,4,1,1,8,5]]

fifth_col = [grid[x][4] for x in range(len(grid))]
print fifth_col

There might be a more graceful replacement for the range(len(grid))  
part.

Yrs,
Eric


More information about the Tutor mailing list