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
  • 133,177
  • 32
  • 312
  • 322
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
  • 15,168
  • 3
  • 22
  • 38
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
  • 133,177
  • 32
  • 312
  • 322