Weird lambda rebinding/reassignment without me doing it

David C. Ullrich dullrich at sprynet.com
Fri Jul 11 18:20:53 CEST 2008


In article 
<f46f5968-c1f4-44a9-972a-164c45195c38 at t54g2000hsg.googlegroups.com>,
 ssecorp <circularfunc at gmail.com> wrote:

> >>> def mod(x,y):
> 	return x.append(y)
> 
> >>> mod([1,2],3)
> >>> k=[1,2,3]
> >>> k
> [1, 2, 3]
> >>> l = mod(k,4)
> >>> l
> >>> k
> [1, 2, 3, 4]
> >>> l
> >>> k==l
> False
> >>> 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
> >>> l=k
> >>> l
> [1, 2, 3, 4, 5]
> >>> i=mod(k,1)
> >>> i
> >>>
> 
> same stuff but i dont find this intuitive.

You need to read the docs. AList.append(x) does _not_
return AList with x appended. In fact it returns None,
because it wants to be a "procedure" that doesn't return
anything at all, but there is no such thing in Python;
functions and methods that do not explicitly contain
a "return" statement return None.

So when you say "return x.append(a)" you're saying
"return None", which explains the rest of it. You
noticed that the second line of

> >>> l = mod(k,4)
> >>> l

didn't print anything? That's because the first line
set l to None. If you'd typed "print l" instead of just "l"
you would have seen

>>> l = mod(k,4)
>>> l
>>> None

-- 
David C. Ullrich



More information about the Python-list mailing list