very good reasons?

Pete Shinners pete at visionart.com
Fri Sep 29 15:38:55 EDT 2000


"Grant Griffin" <g2 at seebelow.org> wrote
> I was trying to chain "sort" and "reverse" together the
> other day <<confess>>,
> ala Perl, but I found that it didn't work, e.g.:
>
>    >>> a=[1,2,3,4]
>    >>> b=a.sort().reverse()
>    Traceback (most recent call last):
>      File "<stdin>", line 1, in ?
>    AttributeError: 'None' object has no attribute 'reverse'
>
> I would have expected sort and reverse to return the list
> in question, but instead they return None.  So I had to do
> something like:
>
>    >>> a=[1,2,3,4]
>    >>> a.sort()
>    >>> a.reverse()
>    >>> b=a
>    >>> b
>    [4, 3, 2, 1]

the reason is to remove ambiguity. there are two options
when calling a method like this...
1) return a new list with the values changed
2) modify the list in place

Python has chosen the keep the two methods from confusing
one another by making the 'in-place' methods return nothing.
this thinking also goes into the assignment operator (=)
returning nothing.

i can understand and appreciate the reasoning behind this
logic, but sometimes it is still makes me jump through
the extra hoops when i don't want.

nonetheless. if you're going to be doing this a lot,
and you'd like a shortcut or two, here are some options.

use the logical or to modify an item in place and return
itself...  "b = a.sort() or a". not quite KISS, but it
can be expanded, "b = a.sort() or a.reverse() or a"

i frequently want a reverse sorted list, and internally
frown apon breaking it up into multiple commands. if
you don't need to assign the list, you can reverse sort
in place with this command "a.sort(lambda x,y: cmp(y,x))"
btw, this is about 25 times slower than "a.sort();a.reverse()"
in my informal testing

lastly, you can define some helper functions to do it
for you. this needs the most code, but least 'hackish'
def reversesortandval(a):
    a.sort()
    a.reverse()
    return a
b = reversesortandval(a)

(there's likely others i haven't thought of)

hopefully this helps. you should understand the reason
why it is, and hopefully these workarounds get get you
through things. as for the complex numbers situation,
i've never used them and have no explanations. :[






More information about the Python-list mailing list