How to sort the objects in a list in Python?

PythonServer Side ProgrammingProgramming

To sort a list of ints, floats, strings, chars or any other class that has implemented the __cmp__ method can be sorted just by calling sort on the list. If you want to sort the list in reverse order(descending), just pass in the reverse parameter as well. 

example

my_list = [1, 5, 2, 6, 0]
my_list.sort()
print(my_list)
my_list.sort(reverse=True)
print(my_list)

Output

This will give the output −

[0, 1, 2, 5, 6]
[6, 5, 2, 1, 0]

Since tuples are immutable, they don't have an in-place sort function that can be called directly on them. You have to use the sorted function, which returns a sorted list. If you dont want to sort the list in place, use sorted in place of the list class method sort. 

example

my_list = [1, 5, 2, 6, 0]
print(sorted(my_list))
print(sorted(my_list, reverse=True))

Output

This will give the output −

[0, 1, 2, 5, 6]
[6, 5, 2, 1, 0]

If you have a list of objects without __cmp__ method implemented in the class, you can use the key argument to specify how to compare 2 elements. For example, if you have dictionaries in a list and want to sort them based on a key size, you could do the following:

Example

def get_my_key(obj):
  return obj['size']
my_list = [{'name': "foo", 'size': 5}, {'name': "bar", 'size': 3}, {'name': "baz", 'size': 7}]
my_list.sort(key=get_my_key)
print(my_list)

Output

This will give the output −

[{'name': 'bar', 'size': 3}, {'name': 'foo', 'size': 5}, {'name': 'baz', 'size': 7}]

It would call the function specified for each entry and sort based on this value for each entry. You could also specify the same function for an object as well, by returning an attribute of the object.

raja
Updated on 18-Feb-2020 11:30:27

Advertisements