Weird lambda rebinding/reassignment without me doing it

MRAB google at mrabarnett.plus.com
Thu Jul 10 19:33:02 EDT 2008


On Jul 10, 9:46 pm, ssecorp <circularf... at gmail.com> wrote:
> >>> def mod(x,y):
>
>         return x.append(y)
>
append adds y to list x and returns None, which is then returned by
mod.

>
>
> >>> mod([1,2],3)
> >>> k=[1,2,3]
> >>> k
> [1, 2, 3]
> >>> l = mod(k,4)
4 has been appended to list k and mod has returned None, so l is now
None.

> >>> l
> >>> k
> [1, 2, 3, 4]
> >>> l
> >>> k==l
> False
Because k is [1, 2, 3, 4] and l is None.

> >>> mod(k,5)
> >>> k
> [1, 2, 3, 4, 5]
> >>> mod(l,4)
>
> Traceback (most recent call last):
>   File "<pyshell#29>", line 1, in <module>
>     mod(l,4)
>   File "<pyshell#18>", line 2, in mod
>     return x.append(y)
> AttributeError: 'NoneType' object has no attribute 'append'
>
l is None, not a list, so it complains!

> >>> l
> >>> l=k
> >>> l
> [1, 2, 3, 4, 5]
> >>> i=mod(k,1)
> >>> i
>
> same stuff but i dont find this intuitive.

It's usual for methods which modify to return None.



More information about the Python-list mailing list