Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a sublist within a Python list of integers

Tags:

python

I have an unsorted list of integers in a Python list. I want to sort the elements in a subset of the full list, not the full list itself. I also want to sort the list in-place so as to not create new lists (I'm doing this very frequently). I initially tried

p[i:j].sort()

but this didn't change the contents of p presumably because a new list was formed, sorted, and then thrown away without affecting the contents of the original list. I can, of course, create my own sort function and use loops to select the appropriate elements but this doesn't feel pythonic. Is there a better way to sort sublists in place?

like image 787
sizzzzlerz Avatar asked Sep 08 '10 14:09

sizzzzlerz


People also ask

How do you sort a list of integers in Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do I sort a nested list?

There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.


1 Answers

You can write p[i:j] = sorted(p[i:j])

like image 116
Jochen Ritzel Avatar answered Oct 01 '22 03:10

Jochen Ritzel