4

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

For example:

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

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

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

I know this can be done by using a sorting algorithm but is there a one line way to do it or a more pythonic way to do this?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Sayan Basu
  • 43
  • 4

2 Answers2

3

You can do so by slice assignment where you replace a slice of a with a sorted slice of a:

>>> a = ['T',4,2,1,3]
>>> a[1:] = sorted(a[1:])
>>> a
['T', 1, 2, 3, 4]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
3

You could slice it, sort the trailing slice and concatenate it afterwards:

>>> a = a[:1] + sorted(a[1:])
>>> a
['T', 1, 2, 3, 4]
MSeifert
  • 145,886
  • 38
  • 333
  • 352