Sorting part of a list

John Machin sjmachin at lexicon.net
Fri Jun 24 08:15:56 EDT 2005


Sibylle Koczian wrote:
> Hello,
> 
> I thought I understood list slices, but I don't. I want to sort only the 
> last part of a list, preferably in place. If I do
> 
>  >>> ll = [3, 1, 4, 2]
>  >>> ll[2:].sort()

It may help in unravelling any bogglement to point out that this is 
equivalent to

temp = ll[2:]; temp.sort(); del temp


>  >>> ll
> [3, 1, 4, 2]
> 
> ll isn't changed, because ll[2:] is a copy of the last part of the list, 
> and this copy is sorted, not the original list. Right so far?

Quite correct.

> 
> But assignment to the slice:
> 
>  >>> ll[2:] = [2, 4]
>  >>> ll
> [3, 1, 2, 4]
> 
> _does_ change my original ll.

Quite correct.

> 
> What did I misunderstand?


What misunderstanding? You have described the behaviour rather 
precisely. Which of the two cases is boggling you?



More information about the Python-list mailing list