[Tutor] 2D list assignment

Gregor Lingl glingl at aon.at
Fri Mar 12 14:23:28 EST 2004



Shitiz Bansal schrieb:

> Hi,
> This is a sample python code:
> a=((2,4),(4,2))
>
>
> a[1][1]=4
> Traceback (most recent call last):
> File "<pyshell#2>", line 1, in -toplevel-
> a[1][1]=4
> TypeError: object doesn't support item assignment
> Is it a bug or am i missing the point?

It's not a bug!

You create a data structure and then try to change it (i.e. it'S content).

In Python there are several types of "sequences", among them:

tuples, which are immutable and
lists which are mutable.

You used a tuple (of tuples), designated by parentheses ()
Instead you should have used lists, designated by brackets [],
because only they are mutable:
 >>> a=[[2,4],[4,2]]
 >>> a[1][1]=4
 >>> a
[[2, 4], [4, 4]]

See Docs: Python Library reference, 2.3.6 Sequence Types
and especially 2.3.6.4 Mutable Sequence Types

Regards,
Gregor


> Shitiz
> ------------------------------------------------------------------------
> Do you Yahoo!?
> Yahoo! Search - Find what you’re looking for faster. 
> <http://search.yahoo.com/?fr=ad-mailsig-home>
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>



More information about the Tutor mailing list