Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list from an index to another index - python [duplicate]

Suppose I have a list [2, 4, 1, 3, 5].

I want to sort the list just from index 1 to the end, which gives me [2, 1, 3, 4, 5]

How can I do it in Python?

(No extra spaces would be appreciated)

like image 221
nwice13 Avatar asked Jan 20 '20 05:01

nwice13


People also ask

How do you sort a list by index in Python?

You can use the python sorting functions' key parameter to sort the index array instead. perhaps key=s. __getitem__ ? In case you also want the sorted array, sorted_s = [s[k] for k in ind_s_to_sort] , where ind_s_to_sort is the index acquired from this method.

How do I find the index of a duplicate element in a list?

Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.

Does sort in Python remove duplicates?

Using sort() We can use the sort() method to sort the set that we obtained in approach 2. This will also remove any duplicates, while preserving the order, but is slower than the dict.


1 Answers

TL;DR:

Use sorted with a slicing assignment to keep the original list object without creating a new one:

l = [2, 4, 1, 3, 5]
l[1:] = sorted(l[1:])
print(l)

Output:

[2, 1, 3, 4, 5]

Longer Answer:

After the list is created, we will make a slicing assignment:

l[1:] = 

Now you might be wondering what does [1:], it is slicing the list and starts from the second index, so the first index will be dropped. Python's indexing starts from zero, : means get everything after the index before, but if it was [1:3] it will only get values that are in between the indexes 1 and 3, let's say your list is:

l = [1, 2, 3, 4, 5]

If you use:

print(l[1:])

It will result in:

[2, 3, 4, 5]

And if you use:

print(l[1:3])

It will result in:

[2, 3]

About slicing, read more here if you want to.

And after slicing we have an equal sign =, that just simply changes what's before the = sign to what's after the = sign, so in this case, we use l[1:], and that gives [2, 3, 4, 5], it will change that to whatever is after the = sign.

If you use:

l[1:] = [100, 200, 300, 400]
print(l)

It will result in:

[1, 100, 200, 300, 400]

To learn more about it check out this.

After that, we got sorted, which is default builtin function, it simple sorts the list from small to big, let's say we have the below list:

l = [3, 2, 1, 4]

If you use:

print(sorted(l))

It will result in:

[1, 2, 3, 4]

To learn more about it check this.

After that we come back to our first topic about slicing, with l[1:], but from here you know that it isn't only used for assignments, you can apply functions to it and deal with it, like here we use sorted.

like image 172
U12-Forward Avatar answered Oct 13 '22 20:10

U12-Forward