Nono.MA

Sort Python list by key

LAST UPDATED FEBRUARY 6, 2023

Here's how to sort a Python list by a key of its items. Check this post if you're looking to sort a list of dictionaries instead.

# A list of people
# name, age, location
people = [
    ['Nono', 32, 'Spain'],
    ['Alice', 20, 'Wonderland'],
    ['Phillipe', 100, 'France'],
    ['Jack', 45, 'Caribbean'],
]

# Sort people by age, ascending
people_sorted_by_age_asc = sorted(people, key=lambda x: x[1])
# [
#     ['Alice', 20, 'Wonderland'],
#     ['Nono', 32, 'Spain'],
#     ['Jack', 45, 'Caribbean'],
#     ['Phillipe', 100, 'France']
# ]

# Sort people by age, descending
people_sorted_by_age_desc = sorted(people, key=lambda x: -x[1])
# [
#     ['Phillipe', 100, 'France'],
#     ['Jack', 45, 'Caribbean'],
#     ['Nono', 32, 'Spain'],
#     ['Alice', 20, 'Wonderland']
# ]

# Sort people by name, ascending
people_sorted_by_name_desc = sorted(people, key=lambda x: x[0])
# [
#     ['Alice', 20, 'Wonderland'],
#     ['Jack', 45, 'Caribbean'],
#     ['Nono', 32, 'Spain'],
#     ['Phillipe', 100, 'France']
# ]

BlogCodePythonTil