How to access elements in a list of lists?

Chris Roy-Smith chris_roysmith at internode.on.net
Mon May 9 00:40:55 EDT 2011


On 09/05/11 13:31, James Mills wrote:
> 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
>
Thanks, that has my understanding problem fixed! And answers what would 
probably be my next question.

Regards
Chris Roy-Smith



More information about the Python-list mailing list