How can I sort a specific range of elements in a list?
11,163
Solution 1
lst = lst[0:1] + sorted(lst[1:])
Solution 2
lst = [5, 3, 5, 1, 4, 7]
lst[1:] = sorted(lst[1:])
print(lst) # prints [5, 1, 3, 4, 5, 7]
Solution 3
so = lambda x, index: x[:index]+sorted(x[index:])
so call it as so(lst, 1)
In [2]: x = [5, 3, 5, 1, 4, 7]
In [3]: so(lst, 1)
Out[4]: [5, 1, 3, 4, 5, 7]
Author by
Synapse
Updated on July 05, 2022Comments
-
Synapse almost 2 years
Suppose I have a list,
lst = [5, 3, 5, 1, 4, 7]
and I want to get it ordered from the second element 3 to the end.
I thought I could do it by:
lst[1:].sort()
But, this doesn't work.
How can I do it?