Estimated reading time: 2 minutes
Why would you sort a list?
It allows efficiency in other algorithms to quickly find data in the list that is used as an input to their code, examples include searching and merging data.
Also, can be used to standardize the data set so that it can have a meaningful representation.
For data visualization purposes having it in order can allow the viewer quickly to attach meaning to what they see in front of them.
There are different sorting techniques as follows:
- Bubble Sort Algorithm is used to arrange N elements in ascending order.
- Selection sort is a straightforward process of sorting values. In this method, you sort the data in ascending order.
- Merge sort splits two lists into a comparable size, sorts them, and then merges them back together.
According to the Python Organisation website, Python lists have a built-in list.sort()
the method that modifies the list in-place.
mylist = [5, 2, 3, 1, 4] mylist.sort() print(mylist) [1, 2, 3, 4, 5]
This method only works for lists.
It also has a very similar method sorted()
, which, unlike list.sort, can work on any iterable.
a= {'c':'1','b':'2','a':'3'} print(sorted(a)) ['a', 'b', 'c']
Note that the sorted method only sorts the key value in the dictionary above.
Per programiz.com parameters for the sorted() function are as follows:
sorted()
can take a maximum of three parameters:
- iterable – A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator.
- reverse (Optional) – If, the sorted list is reversed (or sorted in descending order). Defaults to if not provided.
- key (Optional) – A function that serves as a key for the sort comparison. Defaults to
None
.
Click how to sort lists in python to get a video tutorial on the above, which may help to explain the concepts further.