How do you sort a list by index?

Python | Sort list of list by specified index

We can sort list of list using the conventional sort function. This sorts the list by the first index of lists. But more than often there can be circumstances that requires the sorting of list of list by other index elements than first. Lets discuss certain ways in which this task can be performed.

Method #1 : Using sort() + lambda
sort() can be used to perform this variation of sort by passing a function as a key that performs the sorting according to the desired inner list index.




# Python 3 code to demonstrate
# to sort list of list by given index
# using sort() + lambda
# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
# printing original list
print ("The original list is : " + str(test_list))
# using sort() + lambda
# to sort list of list
# sort by second index
test_list.sort(key = lambda test_list: test_list[1])
# printing result
print ("List after sorting by 2nd element of lists : " + str(test_list))

Output :

The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]] List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]

Method #2 : Using sorted() + itemgetter()
This can also be applied to perform this particular task. The advantage that it holds is that it does not modify the original list. itemgetter() is used to get the index element by which the sort operation needs to be performed.




# Python3 code to demonstrate
# to sort list of list by given index
# using sorted() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
# printing original list
print ("The original list is : " + str(test_list))
# using sort() + lambda
# to sort list of list
# sort by second index
res = sorted(test_list, key = itemgetter(1))
# printing result
print ("List after sorting by 2nd element of lists : " + str(res))

Output :

The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]] List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]




Article Tags :
Python
Sorting
Python list-programs
python-list
Practice Tags :
python-list
Sorting
Read Full Article

Python | Returning index of a sorted list


Sort a list in python and then return the index of elements in sorted order.

Examples:

Input : [2, 3, 1, 4, 5] Output : [2, 0, 1, 3, 4] After sorting list becomes [1, 2, 3, 4, 5] and their index as [2, 0, 1, 3, 4] Input : [6, 4, 7, 8, 1] Output : [4, 1, 0, 2, 3] After sorting the list becomes [1, 4, 6, 7, 8] and their index as [4, 1, 0, 2, 3].

Method 1




import numpy
s = numpy.array([2, 3, 1, 4, 5])
sort_index = numpy.argsort(s)
print(sort_index)

Output :

[2, 0, 1, 3, 4]

Method 2




s = [2, 3, 1, 4, 5]
li=[]
for i in range(len(s)):
li.append([s[i],i])
li.sort()
sort_index = []
for x in li:
sort_index.append(x[1])
print(sort_index)

Output:

[2, 0, 1, 3, 4]

Article Tags :
Python
Sorting
Python list-programs
Python-Sorted
Practice Tags :
Sorting
Read Full Article

Sort a List of Lists in Python

Python Python List

Created: June-02, 2021

A list is one of the most powerful data structures used in Python. We can sort a list in Python by arranging all its elements in ascending or descending order based on the requirement.

We can also have nested lists in Python. These can be thought of as a list of lists. Sorting a list of lists arranges all the inner lists according to the specified index as the key.

In this tutorial, we will sort a list of lists in Python based on some indexes.

Python Advanced List Tutorial

Python Advanced List includes the following concepts.

Let’s explore each of them in detail with examples.

#1) Python Sort List

The sort() method is used to sort the elements in a specific order i.e. Ascending or Descending.

If you want to sort the elements in Ascending order, then you can use the following syntax.

list.sort()

If you want to sort the elements in Descending order, then you can use the following syntax.

list.sort(reverse=True)

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny'] Students.sort() print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]

Now let’s see, How to sort the list in a Descending Order.

Input:

Students = ['Harsh', 'Andrew', 'Danny'] Students.sort() print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]

Thus sort() method is used to arrange a list in either Ascending or Descending order. One more important thing to remember here is that sort() method changes the order of the list permanently. If you want to change the order of the list temporarily, then you need to use sorted() function.

#2) Sorted function

In order to maintain the original order of the list that is present in sorted order, you can use the sorted() function. The sorted() function allows you to display your list in a particular order, without affecting the actual order of the list.

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny'] print(sorted(Students)) print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]
[‘Harsh’, ‘Andrew’, ‘Danny’]

As you can see from the output, the original order of the list remains intact.

You can also print the list in a reverse order using the sorted function in the following manner:

Input:

Students = ['Harsh', 'Andrew', 'Danny'] print(sorted(Students)) print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]
[‘Harsh’, ‘Andrew’, ‘Danny’]

#3) Python Reverse List

In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method.

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny'] Students.reverse() print(Students)

Output:

[‘Danny’, ‘Andrew’, ‘Harsh’]

reverse() method reverses the sequence of the list permanently. Hence in order to get back to the original sequence of the list apply the reverse() method again to the same list.

#4) Python List Index

Index method is used to find a given element in the list and return to its position.

If the same element is present more than once, then it returns the position of the first element. The index in python starts from 0.

Example:

Input:

Students = ['Harsh','Andrew','Danny','Ritesh','Meena'] print(Students.index('Danny'))

Output:

2

Screenshot:

The list.sort() method takes another function as an optional key argument that allows you to modify the default sorting behavior. The key function is then called on each list element and returns another value based on which the sorting is done. Hence, the key function takes one input argument (a list element) and returns one output value (a value that can be compared).

Here’s an example:

>>> lst = [(1,2), (3,2), (3,3), (1,0), (0,1), (4,2), (1,1), (0,2), (0,0)] >>> lst.sort() >>> lst [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (3, 2), (3, 3), (4, 2)] >>> lst.sort(key=lambda x: x[0]) >>> lst [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (3, 2), (3, 3), (4, 2)] >>> lst.sort(key=lambda x: x[1]) >>> lst [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2), (3, 2), (4, 2), (3, 3)]

You can see that in the first two examples, the list is sorted according to the first tuple value first. In the third example, the list is sorted according to the second tuple value first. You achieve this by defining a key function key=lambda x: x[1] that takes one list element x (a tuple) as an argument and transforms it into a comparable value x[1] (the second tuple value).

Related article:

  • An Introduction to Lambda Functions in Python

Python List Sort Itemgetter

You can use any function as a key function that transforms one element into another (comparable) element.

For example, it’s common to use the itemgetter() function from the operator module to access the i-th value of an iterable:

>>> from operator import itemgetter >>> customers = [('alice', 1000), ('bob', 100), ('frank', 10)] >>> customers.sort(key=itemgetter(1)) [('frank', 10), ('bob', 100), ('alice', 1000)]

The itemgetter() function does exactly the same as the lambda function in the previous example: it returns the second tuple value and uses it as a basis for comparison.

Python List Sort with Two Keys

How to sort a list with two keys? For example, you have a list of tuples [(1,2), (3,2), (3,3), (1,0), (0,1), (4,2), (1,1), (0,2), (0,0)] and you want to sort after the second tuple value first. But if there’s a tie (e.g. (1,2) and (3,2)), you want to sort after the first tuple value. How can you do that?

Per default, Python sorts tuples lexicographically—the first tuple value is considered first. Only if there’s a tie, it takes the second tuple value and so on.

So to sort with “two keys”, you can define a key function that returns a tuple rather than only a single tuple value. Here’s an example:

>>> lst = [(1,2), (3,2), (3,3), (1,0), (0,1), (4,2), (1,1), (0,2), (0,0)] >>> lst.sort(key=lambda x: (x[1], x[0])) >>> lst [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2), (3, 2), (4, 2), (3, 3)]

The second tuple value takes precedence over the first tuple value.

Python List Sort with Multiple Keys

How to sort a list with multiple keys? For example, you have a list of tuples [(1,1,2), (0,0,1), (0,1,0), (0,1,2), (1,4,0)] and you want to sort after the second tuple value first. But if there’s a tie (e.g. (0,1,0) and (1,1,2)), you want to sort after the third tuple value. If there’s another tie, you want to sort after the first tuple value. How can you do that?

Per default, Python sorts tuples lexicographically—the first tuple value is considered first. Only if there’s a tie, it takes the second tuple value and so on.

So to sort with “two keys”, you can define a key function that returns a tuple rather than only a single tuple value. Here’s an example:

>>> lst = [(1,1,2), (0,0,1), (0,1,0), (0,1,2), (1,4,0)] >>> lst.sort() >>> lst [(0, 0, 1), (0, 1, 0), (0, 1, 2), (1, 1, 2), (1, 4, 0)] >>> lst.sort(key=lambda x: (x[1],x[2],x[0])) >>> lst [(0, 0, 1), (0, 1, 0), (0, 1, 2), (1, 1, 2), (1, 4, 0)]

The second tuple value takes precedence over the third tuple value. And the third tuple value takes precedence over the first tuple value.

Video liên quan

Postingan terbaru

LIHAT SEMUA