[Tutor] Problems changing a list item in place ?

Kirby Urner urnerk@qwest.net
Mon, 11 Feb 2002 09:35:23 -0800


At 11:56 AM 2/11/2002 -0500, Chris McCormick wrote:
>Hello all,
>     I have a program with a two-dimensional list called map.

'map' is a built-in function -- best to not use it
as a variable name.  Going

   map = []

will wipe out your ability to use the native map
function.

>After it has already been populated, I want to do this:
>
>      map[y_box][x_box][0] = selected_tile

This looks like a three dimensional list.  A 2-d list
would have only 2 subscripts, e.g. here's a two-dimensional
list of [pet, petname] elements:

   >>> pets
   [['dog', 'rover'], ['cat', 'moon']]

To change the name of the cat, I could go:

   >>> pets[1][1] = 'fiesta'
   >>> pets
   [['dog', 'rover'], ['cat', 'fiesta']]

A 3 dimension list would like like:

   [[['a','b'],['c','d']],[['e','f'],['g','h']]]

   >>> themap =   [[['a','b'],['c','d']],[['e','f'],['g','h']]]
   >>> themap[0][1][1]
   'd'
   >>> themap[1]
   [['e', 'f'], ['g', 'h']]
   >>> themap[1][1][1]
   'h'

>      But I get this error:
>
>    File "map_edit.py", line 270, in main
>     map[y_box][x_box][0] = selected_tile                        # Change 
> value of the tile
>TypeError: object doesn't support item assignment
>
>   y_box and x_box are indexes; the statement "print map[y_box][x_box]" 
> works fine.  selected_tile is just an integer, though it shouldn't matter.

Sounds like you probably do have a 2-d list, but you're
trying to index on an element.  It'd be like, using the pets
example, going:

   >>> pets[1][1][0] = 'fiesta'
   Traceback (most recent call last):
     File "<pyshell#26>", line 1, in ?
       pets[1][1][0] = 'fiesta'
   TypeError: object doesn't support item assignment

Note same error message.

The interpreter is saying "wait a minute, you're trying to
stuff 'fiesta' into 'moon' as its 0th member.  But 'moon'
isn't a list.  It's a string.  'string'[index] = object
is not legal syntax.

       map[y_box][x_box] = selected_tile

is what you need to do (but again, it's unfortunate to use
the variable name map).

>I thought you could change list items in-place by assignment.  Are 
>multi-dimensional lists different?

You have too many indexes.  2-d means two indexes, but
you were making it 3 by puting that [0] on the end.

>Thanks in advance,
>Chris

Kirby