[Tutor] Problems changing a list item in place ?
Mon, 11 Feb 2002 09:35:23 -0800
At 11:56 AM 2/11/2002 -0500, Chris McCormick wrote:
> 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
>After it has already been populated, I want to do this:
> map[y_box][x_box] = 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:
[['dog', 'rover'], ['cat', 'moon']]
To change the name of the cat, I could go:
>>> pets = 'fiesta'
[['dog', 'rover'], ['cat', 'fiesta']]
A 3 dimension list would like like:
>>> themap = [[['a','b'],['c','d']],[['e','f'],['g','h']]]
[['e', 'f'], ['g', 'h']]
> But I get this error:
> File "map_edit.py", line 270, in main
> map[y_box][x_box] = 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
>>> pets = 'fiesta'
Traceback (most recent call last):
File "<pyshell#26>", line 1, in ?
pets = '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  on the end.
>Thanks in advance,