list.sort()
Magnus Lie Hetland
mlh at idi.ntnu.no
Sun Jun 17 14:40:50 EDT 2001
"Rikard Bosnjakovic" <bos at hack.org> wrote in message
news:3B2CEBF1.CCF5377D at hack.org...
> 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[:]
result.sort()
return result
Perhaps not very nice, but...
--
Magnus Lie Hetland http://www.hetland.org
"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