0

Might be a silly question but taking a course we just talked about lambda and how it can be used. One of our exercises was to sort a list based on second number in tuples. Example list:

a = [(0, 2), (4, 3), (9, 9), (10, -1)]

Sort based on the numbers 2, 3, 9, and -1 for an expected result of:

[(10, -1), (0, 2), (4, 3), (9, 9)]

My code was the following:

print(a.sort(key=lambda num: num[1]))

The correct answer is:

a.sort(key=lambda x: x[1])
print(a)

Seeing how I essentially had the same answer, this leads me to think I had the order of operations incorrect somewhere. The output of my code was "None" and the output of the correct answer is the expected result above.

What am I missing here? Is there another way to do it correctly?

parrtakenn
  • 37
  • 4
  • So when you wrote your code, how did you know whether it worked or not? – quamrana Nov 22 '22 at 19:40
  • 2
    `list.sort` is in place, so `a.sort(key=lambda x: x[1])` returns nothing, and `print(a.sort(key=lambda x: x[1]))` would incorrectly display `None`. – mozway Nov 22 '22 at 19:41
  • 1
    Does this answer your question? [What is the difference between \`sorted(list)\` vs \`list.sort()\`?](https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort) – cafce25 Nov 22 '22 at 19:41
  • @mozway how can I get it to return the sorted list within print() or is it required to do the sort and then print the sorted list? – parrtakenn Nov 22 '22 at 20:23
  • So if I understand right, a.sort() performs an operation on the list a but having a.sort() within the print() does not return anything because it is performing the operation of sort on list a hence why says "None"? And to get the sorted list after the operation has been performed we do print(a) to get the sorted list? – parrtakenn Nov 22 '22 at 20:26
  • 1
    Did you follow the link provided by cafce25? – quamrana Nov 22 '22 at 20:27
  • 1
    @parrtakenn use `print(sorted(a, key=lambda num: num[1]))` – mozway Nov 22 '22 at 20:42
  • Thank you all, very helpful in understanding the topic. – parrtakenn Nov 22 '22 at 22:10

0 Answers0