a=[1,2,3,4].reverse() - why "a" is None?

Andre Engels andreengels at gmail.com
Mon Oct 12 13:23:50 CEST 2009


On Mon, Oct 12, 2009 at 10:44 AM, Nadav Chernin
<Nadav.C at qualisystems.com> wrote:
>
>        Chris Withers wrote:
>
>        ...becauase you were looking for:
>
>        reversed([1,2,3,4])
>
> OK, but my question is generic. Why when I use object's function that
> changed values of the object, I can't to get value of it on the fly
> without writing additional code?
>
>>>> a=[1,3,2,4]
>>>> a.sort()
>>>> a.reverse()
>>>> a
> [4, 3, 2, 1]
>
> Why I can't a==[1,3,2,4].sort().reverse() ?

I think it is to avoid programming mistakes. If reverse() or sort()
returned the reversed or sorted list, people are prone to using them
for that purpose, and you get people wondering why

b = [1,2,3,4]
a = b.reverse()

would change the value of b.

By having functions and methods have either return a value but not
have a side effect (that is, changing variables or objects), or have a
side effect but not return a value, one eliminates the risk that
people use a function to obtain a value but do not realize its side
effect.


-- 
André Engels, andreengels at gmail.com



More information about the Python-list mailing list