Magnus Lie Hetland mlh at
Sun Jun 17 20:40:50 CEST 2001

"Rikard Bosnjakovic" <bos at> wrote in message
news:3B2CEBF1.CCF5377D at
> I know the sort-method on lists changes the list in-place and doesn't
> return anything, but I'm still confused.
> Take these examples:
> >>> l = [4,3,2]
> >>> l = l
> >>> l
> [4, 3, 2]
> The list is unchanged, even after assigning it to itself. But:
> >>> l = l.sort()
> >>> l
> >>> print l
> None

Naturally. As you yourself said, sort doesn't return anything, i.e.
l.sort() evaluates to None. When assigning None to l, l becomes None.
Simple :)

> If we split the problem into parts, "l.sort()" sorts l and it becomes
> [2,3,4].

Yes, l becomes [2,3,4] and l.sort() returns None.

> I expected it to be [2,3,4] after assigning it to itself (after
> it got sorted),

That's not what you did. You would have to do this:

>>> l.sort()
>>> l = l

> but the list seem to got deleted instead. I don't like
> this behaviour, at all.

Well, what is usually said in these situations is - "write yourself
a function":

def sort(some_list):
    result = some_list[:]
    return result

Perhaps not very nice, but...


  Magnus Lie Hetland

 "Reality is that which, when you stop believing in
  it, doesn't go away."           -- Philip K. Dick

More information about the Python-list mailing list