Python sorting
sorted() : returns a new list
list.sort() : modifies the list in-place and only defined for list
Let’s look at some example :
using sorted()
1 | example = [7,4,3,1,2] |
example not ordered after calling sorted:
output : 7, 4, 3, 1, 2
1 | after_sort = sorted(example) |
assign to new list after_sort
output : 1, 2, 3, 4, 7
using list.sort()
1 | example.sort() |
output is sorted : 1, 2, 3, 4, 7
using itemgetter()
1 | from operator import itemgetter |
first order by number (itemgetter(1))
then order by alphabet ( itemgetter(0))
output : [[‘G’, 4], [‘A’, 10], [‘B’, 10], [‘C’, 10], [‘D’, 10]]
1 | from operator import itemgetter |