They are both built-in functions, the difference is:
- sort() is one of list's method
- sorted() builds a new sorted list from an iterable
sort()
Eg:
>>> a = [5,2,4,3,1]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
PS:It is just suitable for list!
sorted(iterable[,key][,reverse])
The default values of key and reverse are respectively None and False.
- key
key specifies a function of one argument that is used to extract a comparison key from each list element - reverse
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed
Eg:
students = {
('join','A',15),
('jane','B',12),
('dave','B',10),
}
# sorted by age
s = sorted(students, key=lambda student:student[2])
print(s)
>>>
[('dave', 'B', 10), ('jane', 'B', 12), ('join', 'A', 15)]
With reverse:
students = {
('join','A',15),
('jane','B',12),
('dave','B',10),
}
# sorted by age
s = sorted(students, key=lambda student:student[2], reverse=True)
print(s)
>>>
[('join', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
BTW:
As a mutable object, list has a method : list.reverse()
The method modifies the sequence in place for economy of space of when reversing a large sequence
Attention:To remind users that operates by side effect, it does not return the reversed sequence
>>> L = [5, 2, 9, 0]
>>> L.reverse()
>>> L
[0, 9, 2, 5]
or
>>> L = [5, 2, 9, 0]
>>> reversed(L)
>>> L
[5, 2, 9, 0]
>>> list(reversed(L))
[0, 9, 2, 5]
Pls notice the difference of results of list.reverse() and reversed()