Magnus Lie Hetland
mlh at idi.ntnu.no
Sun Jun 17 20:40:50 CEST 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
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.
> If we split the problem into parts, "l.sort()" sorts l and it becomes
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 = 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
result = some_list[:]
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