How to access elemenst in a list of lists?

James Mills prologic at shortcircuit.net.au
Sun May 8 23:31:30 EDT 2011


On Mon, May 9, 2011 at 1:23 PM, Chris Angelico <rosuav at gmail.com> wrote:
>> Just learning python.
>> I can see that I can address an individual element of a list of lists by
>> doing something like:
>> row = list[5]
>> element = row[3]

This is the correct approach.

Here's an interactive example (tested):

$ python
Python 2.7.1 (r271:86832, Feb  8 2011, 10:07:16)
[GCC 4.5.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> grid = [[" " for x in range(5)] for y in range(5)]
>>> from pprint import pprint
>>> pprint(grid)
[[' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' ']]
>>> grid[2][2] = "X"
>>> pprint(grid)
[[' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', 'X', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' ']]
>>>

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"



More information about the Python-list mailing list