Python Sorting Techniques: sort() vs sorted()

In Python, there are two methods for sorting: the built-in sort() method for lists and the global sorted() fnuction.

Key differences:

  • The sort() method modifies the original list and does not return a new list. It is limited to sorting lists.
  • The sorted() function returns a new list, leaving the original unchanged. It can be used with any iterable object.

Syntax for sort(): list.sort(cmp=None, key=None, reverse=False)

  • cmp: optional paramter; if specified, it uses this method for sorting.
  • key: specifies the element to use for comparison. The function takes one arguement, which is an element from the iterable.
  • reverse: sorting order. reverse=True sorts in descending order, while reverse=False (default) sorts in ascending order.
#!/usr/bin/python
# -*- coding: UTF-8 -*-

def get_second_element(item):
    return item[1]

random_list = [(2, 2), (3, 4), (4, 1), (1, 3)]
random_list.sort(key=get_second_element)
print('Sorted list:', random_list)

Syntax for sorted(): sorted(iterable, cmp=None, key=None, reverse=False)

  • iterable: an iterable object.
  • cmp: a comparison function that takes two arguments. The function should return 1 if the first argument is greater, -1 if it is smaller, and 0 if they are equal.
  • key: similar to the sort() method, it defines the element used for comparison.
  • reverse: sorting order as described above.
# Using cmp
>>> data = [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
>>> sorted(data, cmp=lambda x, y: cmp(x[1], y[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

# Using key
>>> sorted(data, key=lambda x: x[1])
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

# Sorting a dictionary
>>> my_dict = {'a': '2', 'c': '5', 'b': '1'}
>>> result = sorted(my_dict)
>>> print(result)
['a', 'b', 'c']

result2 = sorted(my_dict, key=lambda x: my_dict[x])
>>> print(result2)
['b', 'a', 'c']

Tags: python Sorting sort sorted

Posted on Fri, 17 Jul 2026 17:12:08 +0000 by daveoliveruk