List Sorting In Python

Techniques to organize your data efficiently

A.I HUB
8 min readJust now
Image By Author

Sorting a list is one of the most fundamental and powerful techniques in Python allowing you to organize data efficiently for better analysis, retrieval or display. Whether you are arranging numbers in ascending order or alphabetizing strings, mastering the ability to sort lists is a crucial skill for any developer. In this article, we will explore the various methods Python offers to sort lists, ensuring that you can handle data sets of any size with ease and precision.

Table of Content

  • Sorting a List
  • Reversing a List
  • Finding an item in the list
  • Comparing Lists
  • Built-in functions used on lists

Sorting a List

The elements of a list can be sorted by using the list sort method. It sorts
the list in-place, which means that it will change your list object. The
elements are sorted in ascending order, they are arranged from smallest
to largest. If the elements are strings, they are sorted according to their

ASCII values. This method returns None.

>>> L = [23, 76, 34, 12, 89, 14]
>>> L.sort()
>>> L

Output

[12, 14, 23, 34, 76, 89]

To change the sorting order, add the argument reverse=True.

>>> L = [23, 76, 34, 12, 89, 14]
>>> L.sort(reverse=True)
>>> L

Output

[89, 76, 34, 23, 14, 12]

The numbers are now sorted from largest to smallest.
Now, let us use the sort method to sort a list of strings.

>>> L = ['Cow', 'Zebra', 'Ant', 'Bear', 'Crow', 'Wolf']
>>> L.sort()
>>> L

Output

['Ant', 'Bear', 'Cow', 'Crow', 'Wolf', 'Zebra']
>>> L.sort(reverse=True)
>>> L

Output

['Zebra', 'Wolf', 'Crow', 'Cow', 'Bear', 'Ant']

We get the results in alphabetical order, but this order will be disturbed if the
list contains strings in both lower case and upper case.

>>> L = ['Cow', 'Zebra', 'Ant', 'bat', 'crow',
'Wolf']
>>> L.sort()
>>> L

Output

['Ant', 'Cow', 'Wolf', 'Zebra', 'bat', 'crow']

In the sorted list, we first have all the uppercase strings and then the

lowercase strings. This is because the strings are sorted according to their
ASCII values. ASCII values of uppercase letters are less than those of
lowercase letters, so uppercase letters come before lowercase letters.
Therefore, the sort method performs a case sensitive sort in the case of

strings. To perform case insensitive sort, to ignore the case while
sorting, you can send str.lower as the argument for the key parameter.

>>> L = ['Cow', 'Zebra', 'Ant', 'bat', 'crow', 'Wolf']
>>> L.sort(key=str.lower)
>>> L

Output

['Ant', 'bat', 'Cow', 'crow', 'Wolf', 'Zebra']

Now, the sorting is done in regular alphabetical order and this is because the
sorting is not done on original strings. The str.lower function is applied
to each string to get a key, and then the sorting is done on those keys. So the
sorting is done on these values, 'cow’, 'zebra’, 'ant’, 'bat’,
'crow’, 'wolf’. The original values of the list remain unchanged they
are not changed to lowercase.
We could do the same thing by sending the str.upper function as the
argument for the key parameter.

>>> L = ['Cow', 'Zebra', 'Ant', 'bat', 'crow', 'Wolf']
>>> L.sort(key=str.upper)
>>> L

Output

['Ant', 'bat', 'Cow', 'crow', 'Wolf', 'Zebra']

Now the sorting is done on these values: 'COW’, 'ZEBRA’, 'ANT’,

'BAT’, 'CROW’, 'WOLF’. You can send any one-argument function for the key parameter, which will

be applied to each element of the list to produce its key. The produced key
will be used for sorting. In the next example, we will use the len function
for the key parameter.

>>> L = ['Cow', 'Zebra', 'Ant', 'bat', 'crow', 'Wolf']
>>> L.sort(key=len)
>>> L

Output

['Cow', 'Ant', 'bat', 'crow', 'Wolf', 'Zebra']

Now, sorting is done on the following values.

len('Cow')->3, len('Zebra')->5, len('Ant')->3,
len('bat')->3, len('crow')->4, len('Wolf')->4

Now, the strings are sorted according to their length. The sort method will not work if the list contains elements of mixed types.

If the list contains all strings or all numbers, it is fine, but when a list

contains elements of unrelated types, you will get an error. For example, a
list of integers and floats will be sorted but sorting a list of integers and
strings will give an error.

>>> L1 = [12.4, 12, 13.77, 88, 9.2]
>>> L1.sort()
>>> L1

Output

[9.2, 12, 12.4, 13.77, 88]
>>> L2 = ['Seven', 'Five', 12, 'Six', 'Two', 300, 99]
>>> L2.sort()

Output

TypeError: '<' not supported between instances of 'int' and 'str'

The list L1 that contains integers and floats is sorted but the list L2 that
contains strings and integers gives TypeError because the types are
unrelated.
The sort method will change the list object in-place, so the original order
of the list elements will be lost. If you do not want to modify your original

list and want just a sorted copy of the original list, you can use the

sorted() built-in function. This function does not sort the list in-place which means that it does not change your list object. It just returns a new list
object that is a sorted copy of the list. The returned list object can be

assigned to another name.

>>> L = [81, 2, 13, 99, 7]
>>> L1 = sorted(L)
>>> L1

Output

[2, 7, 13, 81, 99]
>>> L

Output

[81, 2, 13, 99, 7]

We can see that the list L has not changed. The arguments for reverse and
key parameters can be used with the sorted function also.

Reversing a List

The reverse method reverses the order of the elements of the list in-place.
It returns None.

>>> L = [2, 5, 3, 1, 7, 4]
>>> L.reverse()
>>> L

Output

[4, 7, 1, 3, 5, 2]

If you do not want your list to be changed, use the reversed built-in

function. This function does not return a list. It returns an iterable object that
has to be converted to a list.

>>> L = [2, 5, 3, 1, 7, 4]
>>> L1 = list(reversed(L))
>>> L1

Output

[4, 7, 1, 3, 5, 2]
>>> L

Output

[2, 5, 3, 1, 7, 4]

We have converted the return value of reversed function to a list and
assigned it to L1. The list L1 contains the elements of list L in reversed
order and the list L remains unchanged.
As we have seen before, we can get a reversed copy of the list by using the

slice L[::-1].

>>> L = [2, 5, 3, 1, 7, 4]
>>> L1 = L[::-1]
>>> L1

Output

[4, 7, 1, 3, 5, 2]
>>> L

Output

[2, 5, 3, 1, 7, 4]

Finding an Item in the List

The membership operators in and not in can be used to check whether
an element is present in the list. If we want to know the index of an element then we can use the index method. It returns the index of the first
occurrence of the item in the list. If the item is not present, then it raises
ValueError. The search can be restricted by providing optional start and
end values.

  • item in L: Returns True if item present in list L, otherwise False.
  • item not in L: Returns True if item not present in list L, otherwise False.
  • L.index(item): Returns the index of the first occurrence of item in the list.
  • L.index(item,i,j): Returns the index of the first occurrence of item in a portion of the

    list starting from index i to index j-1.

First, let us check the presence of an item in a list using the in operator.

>>> numbers = [82, 31, 55, 12, 7, 56, 99, 12, 99, 67, 12]
>>> 31 in numbers

Output

True
>>> 31 not in numbers

Output

False
>>> 100 not in numbers

Output

True

Now, let us use the index method.

>>> numbers.index(12)

Output

3

We get the index of the first occurrence of 12 in the list. Let us specify a
start value for searching.

>>> numbers.index(12, 4)

Output

7

Now, item 12 was searched in the portion of the list starting from index 4 till
the end of the list. We can specify an end value also.

>>> numbers.index(12, 4, 10)

Output

7

The search was done from index 4 to index 9. If the searched item is not
present in the list, then ValueError is raised.

>>> numbers.index(100)

Output

ValueError: 100 is not in list

To count the number of occurrences of an item, we can use the method
count. If the item is not present in the list, it will return 0.

>>> numbers.count(12)

Output

3

Comparing Lists

The == and != operators can be used to compare two lists for value equality.
The == operator will evaluate to True if the lists have the same content while the != operator will evaluate to True if the contents of the list are
different. The lists are compared element by element starting from the first
index till the last index.

>>> L1 = [1, 2, 3]
>>> L2 = [1, 2, 3]
>>> L3 = [1, 20, 30]
>>> L1 == L2

Output

True
>>> L1 != L3

Output

True
>>> L2 == L3

Output

False

If you want to check whether the two lists refer to the same object, you can
use the is and is not operators.

>>> L4 = L1
>>> L1 is L2

Output

False
>>> L1 is L4

Output

True
>>> L1 is not L4

Output

False

You can also use <, <=, >, and >= operators with lists. These operators will
work only if the lists contain compatible types of data that support greater-than and less-than comparisons.

>>> L1 = [1, 2, 3, 4, 5, 6,7]
>>> L2 = [1, 2, 3, 7, 8]
>>> L1 < L2

Output

True

The two lists are compared element by element till there is a mismatch in the
elements being compared. The result will be the result of comparing the two

mismatched elements. For example, here, mismatched elements are 4 and 7
since 4 is smaller, L1 is considered smaller than L2.

Built-in Functions Used on Lists

We have already seen how the built-in functions sorted and reversed
can be used with lists. Here are some more built-in functions that can work
with lists.

  • len(L): Returns the size of the list.
  • min(L): Returns the smallest value of the list.
  • max(L): Returns the largest value of the list.
  • sum(L): Returns the sum of all the elements of the list if the elements are of numeric type.
>>> numbers = [82, 31, 55, 12, 7, 56, 99, 12, 99, 67, 12]
>>> len(numbers)

Output

11
>>> max(numbers)

Output

99
>>> min(numbers)

Output

7
>>> sum(numbers)

Output

532
>>> average = sum(numbers)/len(numbers)
>>> average

Output

48.36363636363637

Conclusion

sorting a list in Python is more than just organizing data, it’s about enhancing the functionality, readability and efficiency of your code. Whether you are working with numeric values, strings or complex custom objects, Python’s built-in sorting methods offer robust and flexible solutions. By mastering sorting techniques, from basic to advanced, you not only streamline your workflows but also unlock the potential to handle larger, more complex datasets with ease. Sorting isn’t just a technical skill, it’s a critical asset in writing clean, optimized code that stands the test of time.

--

--

A.I HUB

A.I HUB is a learning platform, where you can learn from all sorts of courses for free we help individuals and youngster by providing quality content.