Sort a list in python (original) (raw)

Last Updated : 06 Oct, 2024

Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting.

Python `

Initializing a list

a = [5, 1, 5, 6]

Sort modifies the given list

a.sort() print(a)

b = [5, 2, 9, 6]

Sorted does not modify the given list

and returns a different sorted list

bs = sorted(b) print(b) print(bs)

`

Output

[1, 5, 5, 6] [5, 2, 9, 6] [2, 5, 6, 9]

This article will cover the basics of sorting lists in Python, including built-in functions, custom sorting, and sorting based on specific criteria.

Table of Content

Python Sorting Methods

Python sort() Method

The sort() method sorts the list in place and modifies the original list. By default, it sorts the list in ascending order.

Python `

Initializing a list

a = [5, 2, 9, 1, 5, 6]

Sorting the list in ascending order

a.sort() print("Sorted list (ascending):", a)

a.sort(reverse=True) print("Sorted list (descending):", a)

`

Output

Sorted list (ascending): [1, 2, 5, 5, 6, 9] Sorted list (descending): [9, 6, 5, 5, 2, 1]

Python sorted() Function

**Python **sorted() function returns a sorted list. It is not only defined for the list and it accepts any iterable (list, tuple, string, etc.). It does not modify the given container and returns a sorted version of it.

Python `

Initializing a list

a = [5, 2, 9, 1, 5, 6]

Sorting the list in descending order

sa = sorted(a) print("Sorted list (ascending):", sa)

sa = sorted(a, reverse=True) print("Sorted list (descending):", sa)

`

Output

Sorted list (ascending): [1, 2, 5, 5, 6, 9] Sorted list (descending): [9, 6, 5, 5, 2, 1]

**Sorting Other Containers :

  1. **Sorting a tuple: The sorted() function converts the tuple into a sorted list of its elements.
  2. **Sorting a set: Since sets are unordered, sorted() converts the set into a sorted list of its elements.
  3. **Sorting a string: This will sort the characters in the string and return a list of the sorted characters.
  4. **Sorting a dictionary: When a dictionary is passed to sorted(), it sorts the dictionary by its keys and returns a list of the keys in sorted order.
  5. **Sorting a list of tuples: The list of tuples is sorted primarily by the first element of each tuple, and secondarily by the second element if the first ones are identical. Python `

Sorting a tuple

a = (10, 12, 5, 1) print(sorted(a))

Sorting a set

s = {'gfg', 'course', 'python'} print(sorted(s))

Sorting a string

st = 'gfg' print(sorted(st))

Attempting to sort a dictionary (it will sort the keys)

d = {10: 'gfg', 15: 'ide', 5: 'course'} print(sorted(d))

Sorting a list of tuples

l = [(10, 15), (1, 8), (2, 3)] print(sorted(l))

`

Output

[1, 5, 10, 12] ['course', 'gfg', 'python'] ['f', 'g', 'g'] [5, 10, 15] [(1, 8), (2, 3), (10, 15)]

Sorting User Defined Object

**Example 1: Using a Separate Method

This code defines a Point class with an initializer that sets the x and y coordinates for point objects. The myFun function takes a point object and returns its x coordinate. A list l of Point objects is created, and then sorted based on their x values using the myFun function as the key in the sort method. Finally, it prints out the x and y coordinates of each Point in the sorted list.

Python `

class Point: def init(self, x, y): self.x = x self.y = y

def myFun(p): return p.x

l = [Point(1, 15), Point(10, 5), Point(3, 8)] l.sort(key=myFun)

for i in l: print(i.x, i.y)

`

**Example 2: Using a __lt__ Method

This version defines the __lt__ method within the Point class and includes the necessary return statement, which compares the x attribute of the instances. Now when you call l.sort(), Python will use this __lt__ method to determine the order of Point objects in the list based on their x values. This will sort the points in ascending order by their x coordinates, and the print output will reflect that order.

Python `

class Point: def init(self, x, y): self.x = x self.y = y

def __lt__(self, other):
    return self.x < other.x

l = [Point(1, 15), Point(10, 5), Point(3, 8)] l.sort()

for i in l: print(i.x, i.y)

`

Sorting with Custom Criteria

Sorting Based on Absolute Values

Sometimes you may want to sort numbers based on their absolute values while preserving their original signs. You can do this by using the key parameter in both the sort() method and the sorted() function.

Python `

a = [1, -5, 10, 6, 3, -4, -9]

Sorting by absolute values in descending order

sa = sorted(a, key=abs, reverse=True) print("Sorted by absolute values:", sa)

`

Output

Sorted by absolute values: [10, -9, 6, -5, -4, 3, 1]

Custom Sorting with Lambda Functions

You can use lambda functions to define custom sorting logic. For example, if you want to sort a list of tuples based on the second element:

Python `

List of tuples

a = [(1, 'one'), (3, 'three'), (2, 'two')]

Sorting by the second element of each tuple

sa = sorted(a, key=lambda x: x[1]) print("Sorted by second element:", sa)

`

Output

Sorted by second element: [(1, 'one'), (3, 'three'), (2, 'two')]

Performance Considerations

When sorting lists, the choice between sort() and sorted() may depend on whether you want to maintain the original list. The sort() method is generally faster since it sorts the list in place. However, if you need to keep the original order, use sorted().

Time Complexity