behavior difference for mutable and immutable variable in function definition

7stud bbxx789_05ss at yahoo.com
Fri May 4 18:39:01 EDT 2007


On May 4, 3:30 pm, jianbing.c... at gmail.com wrote:
> Hi,
>
> Can anyone explain the following:
>
> Python 2.5 (r25:51908, Apr  9 2007, 11:27:23)
> [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> def foo():
>
> ...     x = 2
> ...>>> foo()
> >>> def bar():
>
> ...     x[2] = 2
> ...
>
> >>> bar()
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 2, in bar
> NameError: global name 'x' is not defined
>
> Thanks,
> Jianbing

The first function is completely irrelevant unless you expect this to
work:

x = 2
x[2] = 2

Traceback (most recent call last):
  File "test1.py", line 2, in ?
    x[2] = 2
TypeError: object does not support item assignment

So that leaves you with:

> >>> def bar():
>
> ...     x[2] = 2
> ...
>
> >>> bar()

Would you expect this to work:

x[2] = 2
print x






More information about the Python-list mailing list