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

February 12th, 2009 | by Will |

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[:]

  1. 5 Responses to “Things that are wrong with Python (3): destructive functions”

  2. By Daniel Lemire on Feb 12, 2009 | Reply

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

  3. By Michael H. on Feb 12, 2009 | Reply

    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.

  4. By Will on Feb 13, 2009 | Reply

    @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:


    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.

  5. By Michael H. on Feb 13, 2009 | Reply

    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.

  6. By Brendan O'Connor on Feb 14, 2009 | Reply

    as for

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

    could do it as a one-liner with

    x = sorted(list + [1])

    little bit lame.

Sorry, comments for this entry are closed at this time.