Will.Whim

A weblog by Will Fitzgerald

Things that are wrong with Python (3): destructive functions

Pythons’s sort and append functions mutate the sequence they work on.

This is wrong. Rather than write x = list.append(1).sort() you have to write:
x = list[:]
x.append(1)
x.sort()

Advertisements

5 responses to “Things that are wrong with Python (3): destructive functions

  1. Daniel Lemire February 12, 2009 at 5:39 pm

    I agree with all of them. But do they still apply in Python 3?

  2. Michael H. February 12, 2009 at 11:52 pm

    Hmm, I guess it doesn’t make it better that this is basically true in Lisp as well?

    (I say “basically” because sort is definitely destructive, but append has that weird rule about the last list being included verbatim, not copied…)

    I don’t know about Python 3 either.

  3. Will February 13, 2009 at 9:47 am

    @Daniel. Yes, they all still apply in Python 3.

    @Michael. In Lisps: (sort (cons 1 (list 2 3)) <) is not destructive. (Lisp idiom of adding to the front of the list, of course). I have come to believe that: obj.fn1.fn2.fn3 is easier on the eyes than (fn3 (fn2 (fn1 obj))) and also decreases namespace issues (the former typically only requires an import of the class name; Lisps require the import of all the methods on the class). But that's a different matter.

  4. Michael H. February 13, 2009 at 9:07 pm

    I seem to be failing reading comprehension here. In Common Lisp, sort is always allowed to be destructive. In your example there, it’s likely not to be, since the elements are in the right order already, but in ACL here:

    CL-USER(30): (setf *b* (cons 2 (list 1 3)))
    (2 1 3)
    CL-USER(31): (sort *b* #'<)
    (1 2 3)
    CL-USER(32): *b*
    (2 3)

    I’m not sure what to say about your namespace example. CL’s method defs and multiple dispatch mean that they’re not “methods on a class” in the same way as Java or Python.

  5. Brendan O'Connor February 14, 2009 at 1:41 am

    as for

    x = list.append(1).sort()

    could do it as a one-liner with

    x = sorted(list + [1])

    little bit lame.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: