-2

With Python, how to sort the lists based on the values in the list (from right to left)?

For example:

[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]

should return

[2003, 5, 21], [2003, 5, 22], [2005, 5, 11], [2005, 6, 21]
5
  • sorted([[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]]) ? Commented Jun 29, 2021 at 4:49
  • 1
    sorted(a) or a.sort() both will do, as the default sorting order is left to right Commented Jun 29, 2021 at 4:49
  • l = [[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]] l.sort() Commented Jun 29, 2021 at 4:49
  • Did no-one else notice the "right to left" bit in the question? It seems to be inconsitent with the expected result. Commented Jun 29, 2021 at 5:04
  • Does this answer your question? sorting a list in python Commented Jun 29, 2021 at 5:22

2 Answers 2

1

Based on your expected result, that's not right-to-left sorting. In that case, the default sort works just fine:

>>> xyzzy = [[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]]
>>> sorted(xyzzy)
[[2003, 5, 21], [2003, 5, 22], [2005, 5, 11], [2005, 6, 21]]

If you did want to sort based on right-to-left order in each sub-list, you can provide a key function/callable which does the work for you. Since you want the same comparison but in reverse, just use the reversed list for the comparison:

>>> sorted(xyzzy, key=lambda x: x[::-1])
[[2005, 5, 11], [2003, 5, 21], [2005, 6, 21], [2003, 5, 22]]
Sign up to request clarification or add additional context in comments.

Comments

1

Use the sorted() in python.

input_list = [2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]
sorted_list = sorted(input_list)

Declaring the input_list like above will create a tuple of lists and input_list.sort() will not work as sort does not support tuple. If you need to use sort(), you have to first convert the tuple of lists to list of lists and then perform sort operation like below.

input_list = [[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]]
input_list.sort()

If you need to sort from left to right, you can use the reverse parameter.

sorted_list = sorted(input_list, reverse=True)

or

input_list.sort(reverse=True)

Note that sorted() will return the sorted list, whereas sort() will replace the input list with the sorted list.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.