Sort a part of a list in place

0 votes
There is a list as such:

a = [4, 8, 1, 7, 3, 0, 5, 2, 6, 9]
 

Now, a.sort() will sort the list in place. What if we want to sort only a part of the list, still in place? In C++ we could write:

int array = { 4, 8, 1, 7, 3, 0, 5, 2, 6, 9 };
int * ptr = array;
std::sort( ptr + 1, ptr + 4 );
 

Is there any other similar way in Python to do the same?
Feb 12, 2019 in Python by ana1504.k
• 7,910 points
3,077 views

1 answer to this question.

0 votes
You can write it as such:

a[i:j] = sorted(a[i:j])

It is not in-place sort either, but fast enough for relatively small segments.

Please note, that Python copies only object references, so the speed penalty won't be that huge compared to a real in-place sort as one would expect.
answered Feb 12, 2019 by SDeb
• 13,300 points

Related Questions In Python

0 votes
4 answers

how to sort a list of numbers without using built-in functions like min, max or any other function?

Yes it is possible. You can refer ...READ MORE

answered Jun 27, 2019 in Python by Arvind
• 3,040 points
183,581 views
0 votes
1 answer

What is the function to randomize the items of a list in-place?

Hello @Roshni, Python has a built-in module called ...READ MORE

answered Jun 26, 2020 in Python by Gitika
• 65,910 points
1,184 views
+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,720 points
1,066 views
+1 vote
8 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
35,177 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,023 views
0 votes
1 answer
0 votes
1 answer

Return a list inside a for loop while iterating over the elements of another list

The print() is getting called multiple times ...READ MORE

answered Sep 22, 2018 in Python by SDeb
• 13,300 points
4,652 views
0 votes
1 answer

How to Reverse a list in Python

You can use the reversed function in ...READ MORE

answered Sep 29, 2018 in Python by SDeb
• 13,300 points
637 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP