Sort list in python from second on element

I want to sort the list, but I want it to be sorted, excluding the first element.

For instance:

a = ['T', 4, 2, 1, 3]

Now I want the list to be sorted, but the first element should remain in its place:

a = ['T', 1, 2, 3, 4]

I know this can be done using a sorting algorithm, but is there a way to do this one or more Python ways to do this?

+4
source share
2 answers

You can do this by the purpose of the slice, where you replace the fragment awith a sorted fragment a:

>>> a = ['T',4,2,1,3]
>>> a[1:] = sorted(a[1:])
>>> a
['T', 1, 2, 3, 4]
+3
source

You can cut it, sort the final slice and concatenate it later:

>>> a = a[:1] + sorted(a[1:])
>>> a
['T', 1, 2, 3, 4]
+3
source

Source: https://habr.com/ru/post/1676317/


All Articles