a=[1,2,3,4].reverse() - why "a" is None?
Diez B. Roggisch
deets at nospam.web.de
Mon Oct 12 05:32:20 EDT 2009
Nadav Chernin 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() ?
This is a FAQ. The reasoning is that operations that modify a collection in
place (the same goes for .sort()) don't return the collection to prevent
errors from creeping up like this:
unsorted = ...
sorted = unsorted.sort()
where the assumption is that unsorted is still that - unsorted.
You can read a lot of the pro + cons on this NG/ML if you google for it, but
you won't reach a change in semantics.
Diez
More information about the Python-list
mailing list