xxxxxxxxxx
>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
xxxxxxxxxx
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
xxxxxxxxxx
stuff_1 = [3, 4, 5, 2, 1]
stuff_1.sort()
print(stuff_1) # Output: [1, 2, 3, 4, 5]
stuff_2 = ['bob', 'john', 'ann']
stuff_2.sort()
print(stuff_2) # Output: ['ann', 'bob', 'john']
stuff_4 = ['book', 89, 5.3, True, [1, 2, 3], (4, 3, 2), {'dic': 1}]
# print(stuff_4.sort())
# This will give us an error
# TypeError: '<' not supported between instances of 'int' and 'str'
xxxxxxxxxx
# Use SortedList if you care about speed.
Installation
!pip install sortedcontainers
Usage:
>>> from sortedcontainers import SortedList
>>> l = SortedList()
>>> l.update([0, 4, 1, 3, 2])
>>> l.index(3)
3
>>> l.add(5)
>>> l[-1]
5