python sort list with lambda key code example

Example 1: how to sort a list in python using lambda

data = [("Apples", 5, "20"), ("Pears", 1, "5"), ("Oranges", 6, "10")]

data.sort(key=lambda x:x[0])
print(data)
OUTPUT
[('Apples', 5, '20'), ('Oranges', 6, '10'), ('Pears', 1, '5')]

from kite.com
^^

Example 2: python lambda key sort

>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Example 3: python sort list with lambda key

#return new list
>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

#sort in place
data = [("Apples", 5, "20"), ("Pears", 1, "5"), ("Oranges", 6, "10")]

data.sort(key=lambda x:x[0])
print(data)
OUTPUT
[('Apples', 5, '20'), ('Oranges', 6, '10'), ('Pears', 1, '5')]

from kite.com