1

Is there a simple way to sort a nested list by any element of the inner list ? We can sort a list with list_name.sort() statement but can we sort by any desired element or even by any desired list elements element ?

books = [
    ['123', 'book1', 25],
    ['243', 'book2', 30],
    ['874', 'book3', 15],
    ['519', 'book4', 20],
    ['745', 'book5', 10]
]
  1. index of inner lists represent prices, I want to sort this list by prices. How can I accomplish this without any fancy loop used ?
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
jwdomain
  • 61
  • 7

2 Answers2

3

This should do the trick, for instance if you wish to sort by the 3rd element of each inner list-

# element to sort by:
elm = 2
books.sort(key=lambda x: x[elm])
books
flakes
  • 21,558
  • 8
  • 41
  • 88
1
books = [
['123', 'book1', 25],
['243', 'book2', 30],
['874', 'book3', 15],
['519', 'book4', 20],
['745', 'book5', 10]
]

# Use sort() method if you don't need to create a new object
books.sort(key=lambda x : x[2])
print(books)

# Use sorted() function if you want a new object
sorted_books = sorted(books, key=lambda x: x[2])
print(sorted_books)
Robin Sage
  • 969
  • 1
  • 8
  • 24