Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

Answer from kennytm on Stack Overflow
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί howto β€Ί sorting.html
Sorting Techniques β€” Python 3.14.4 documentation
February 23, 2026 - >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] >>> standard_way = sorted(data, key=itemgetter(0), reverse=True) >>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0)))) >>> assert standard_way == double_reversed >>> standard_way [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)] The sort routines use < when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an __lt__() method: >>> Student.__lt__ = lambda self, other: self.age < other.age >>> sorted(student_objects) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί lambda-sort-list-in-python
Lambda Sorted in Python – How to Lambda Sort a List
March 16, 2023 - In this article, you’ll learn how to sort a list with the lambda function. ... You can sort a list with the sort() method and sorted() function. The sort() method takes two parameters – key and reverse.
Discussions

python - Reverse sort order for part of a key - Stack Overflow
TL;DR: You can sort twice, adding a reversed=True argument where needed. Sort by the tiebreaker first. This works because sorting is stable in Python. More on stackoverflow.com
🌐 stackoverflow.com
python - Syntax behind sorted(key=lambda: ...) - Stack Overflow
To define lambda, you specify the object property you want to sort and python's built-in sorted function will automatically take care of it. If you want to sort by multiple properties then assign key = lambda x: (property1, property2). To specify order-by, pass reverse= true as the third ... More on stackoverflow.com
🌐 stackoverflow.com
how does key argument in sorted() works with lambda function
The lambda is called with each element internally. This simple filter variant might make how lambdas can be used clearer: def my_filter(predicate, items): new_list = [] for item in items: # Call the passed function (lambda) if predicate(item): new_list.append(item) return new_list print(my_filter(lambda n: n > 5, range(10))) # Prints [6, 7, 8, 9] The difference between the cases is here, my_filter is using the passed function to do filtering. With sorted, it's using the passed function to access members (or something similar) of each element. More on reddit.com
🌐 r/learnpython
13
2
January 14, 2023
Sorting by absolute values(for special cases)(without lambda)

I don't think you can. Why don't you want to use a lambda? It would just be:

sorted(k, key=lambda x: (x[0], abs(x[1]))
More on reddit.com
🌐 r/learnpython
11
1
November 25, 2022
🌐
FavTutor
favtutor.com β€Ί blogs β€Ί python-sort-lambda
How to Sort with Lambda in Python | 7 Methods (With Code)
September 15, 2023 - By default, the `sorted()` function sorts in ascending order. You can use a lambda function to reverse the sorting order.
🌐
Spark By {Examples}
sparkbyexamples.com β€Ί home β€Ί python β€Ί sort using lambda in python
Sort using Lambda in Python - Spark By {Examples}
May 9, 2024 - The default is reverse=False. The key function is an optional parameter that can be used to specify how the items should be sorted. When you use key=lambda, The lambda function is applied to each item in the list, and the resulting values are ...
🌐
Imperial College London
python.pages.doc.ic.ac.uk β€Ί 2022 β€Ί lessons β€Ί core10 β€Ί 05-lambda β€Ί 03-sorted.html
Lesson 10: I am Your Father > Lambda in sorted() | Python Programming (70053 Autumn Term 2022/2023) | Department of Computing | Imperial College London
freq = {"python": 24, "cat": 78, "mat": 12, "aardvark": 1, "fish": 56} sorted_tuples = sorted(freq.items(), key=lambda x:x[1], reverse=True) print(sorted_tuples) ## [('cat', 78), ('fish', 56), ('python', 24), ('mat', 12), ('aardvark', 1)]
Find elsewhere
Top answer
1 of 1
4

TL;DR: You can sort twice, adding a reversed=True argument where needed. Sort by the tiebreaker first. This works because sorting is stable in Python.


Using - attribute2 instead of attribute2 inside the tuple is the easiest way if attribute2 is a number.

If attribute2 is a string, or something else that cannot be multiplied by -1 in a meaningful way, then this trick doesn't work.

However, note that lst.sort and sorted are guaranteed to be stable sorts in python. In particular, this means that the two following code snippets are equivalent:

# SORT ACCORDING TO A TUPLE
l.sort(key=lambda x: (x[0], x[1]))

# SORT TWICE
l.sort(key=lambda x: x[1])
l.sort(key=lambda x: x[0])

Note how in the second version, we sorted by the tie-breaker first, then by the main criterion.

With the first version, we can sort in decreasing order of one of the two criterion by multiplying it by -1, if this criterion is numeric:

l.sort(key=lambda x: (x[0], -x[1]))

With the second version, however, we can sort in decreasing order of one of the two criterion, using optional argument reverse=True, and this works for numbers as well as for other types, for instance strings.

l.sort(key=lambda x: x[1], reverse=True)
l.sort(key=lambda x: x[0])

Finally, note that instead of defining a custom function with def or lambda to use as the sorting key, you can use operator.itemgetter or operator.attrgetter.

For instance, the following two code snippets are equivalent:

# FIRST VERSION
l.sort(key=lambda x: (x[0], x[1]))

# SECOND VERSION
from operator import itemgetter
l.sort(key=itemgetter(0, 1))

The following three code snippets are equivalent:

# FIRST VERSION
def mykey(x):
    x1 = x.attribute1
    x2 = x.attribute2
    return (x1, x2)
l.sort(key=mykey)

# SECOND VERSION
l.sort(key=lambda x: (x.attribute1, x.attribute2))

# THIRD VERSION
from operator import attrgetter
l.sort(key=attrgetter('attribute1', 'attribute2'))
🌐
Real Python
realpython.com β€Ί python-sort
How to Use sorted() and .sort() in Python – Real Python
February 24, 2025 - Each element will have reverse_word() applied to it, and the sorting order will be based on the characters in the reversed version of each word. If two words have the same final letter, the next letter is compared, and so on.
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί python-program-to-sort-the-list-according-to-the-column-using-lambda
Python Program to Sort the list according to the column using lambda - GeeksforGeeks
July 12, 2025 - The list is sorted numerically by the second column. We can use the sorted() function with the reverse=True parameter, and specify the column (or element) by which we want to sort using the key parameter (if necessary).
🌐
Blogboard
blogboard.io β€Ί blog β€Ί knowledge β€Ί python-sorted-lambda
Python sort lambda - How to sort with lambda key function in Python
February 5, 2023 - Note that sorted always sorts in ascending order unless we modify its behaviour using key or reverse parameters. Understanding how lists of tuples or lists of lists are sorted is crucial to understanding more complex sorting patterns - those using the key parameter. In our previous example, what if we wanted to sort the movies by rating first, then by year? Python's sorted function offers a simple solution - use the key parameter.
🌐
LabEx
labex.io β€Ί tutorials β€Ί python-how-to-use-a-lambda-function-for-custom-sorting-in-python-415786
How to use a lambda function for custom sorting in Python | LabEx
The first element in the tuple is the primary sorting key, and subsequent elements are used for tie-breaking. We used a negative sign -student["age"] to sort by age in descending order. This technique is useful when you want to sort numerically ...
🌐
GitHub
gist.github.com β€Ί yangshun β€Ί ffaf68380ef71c157c3b
Sort then reverse vs Sort(reverse=True) Β· GitHub
Sort then reverse vs Sort(reverse=True). GitHub Gist: instantly share code, notes, and snippets.
🌐
DEV Community
dev.to β€Ί kiani0x01 β€Ί how-to-sort-in-python-using-lambda-obg
How to sort in Python using Lambda - DEV Community
August 11, 2025 - Lambdas shine here: users = [ {'name': ... sorted_by_age = sorted(users, key=lambda u: u['age'], reverse=True) Use reverse=True to flip the sort order....
🌐
W3Schools
w3schools.com β€Ί python β€Ί ref_func_sorted.asp
Python sorted() Function
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values. ... a = ("h", "b", "a", "c", "f", "d", "e", "g") x = sorted(a, reverse=True) print(x) Try it Yourself Β»
🌐
Linux Hint
linuxhint.com β€Ί sort-lambda-python
How to sort with lambda in Python – Linux Hint
# Declare the list of dictionary ... i['name'], reverse=True)) The following output will appear after executing the above script. The uses of lambda for sorting four different lists have shown in this tutorial by using simple examples that will help the python users to understand ...
Top answer
1 of 10
293

I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.

For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.

For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.

  1. Using lamba ultimately means you don't have to write (define) an entire function. Lambda functions are created, used, and immediately destroyed - so they don't funk up your code with more code that will only ever be used once. This, as I understand it, is the core utility of the lambda function and its application for such a role is broad. Its syntax is purely a convention, which is in essence the nature of programmatic syntax in general. Learn the syntax and be done with it.

Lambda syntax is as follows:

lambda input_variable(s): tasty one liner

where lambda is a python keyword.

e.g.

In [1]: f00 = lambda x: x/2

In [2]: f00(10)
Out[2]: 5.0

In [3]: (lambda x: x/2)(10)
Out[3]: 5.0

In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0

In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
  1. The idea behind the key argument is that it should take in a set of instructions that will essentially point the 'sorted()' function at those list elements which should be used to sort by. When it says key=, what it really means is: As I iterate through the list, one element at a time (i.e. for e in some_list), I'm going to pass the current element to the function specifed by the key argument and use that to create a transformed list which will inform me on the order of the final sorted list.

Check it out:

In [6]: mylist = [3, 6, 3, 2, 4, 8, 23]  # an example list
# sorted(mylist, key=HowToSort)  # what we will be doing

Base example:

# mylist = [3, 6, 3, 2, 4, 8, 23]
In [7]: sorted(mylist)
Out[7]: [2, 3, 3, 4, 6, 8, 23]  
# all numbers are in ascending order (i.e.from low to high).

Example 1:

# mylist = [3, 6, 3, 2, 4, 8, 23]
In [8]: sorted(mylist, key=lambda x: x % 2 == 0)

# Quick Tip: The % operator returns the *remainder* of a division
# operation. So the key lambda function here is saying "return True 
# if x divided by 2 leaves a remainer of 0, else False". This is a 
# typical way to check if a number is even or odd.

Out[8]: [3, 3, 23, 6, 2, 4, 8]  
# Does this sorted result make intuitive sense to you?

Notice that my lambda function told sorted to check if each element e was even or odd before sorting.

BUT WAIT! You may (or perhaps should) be wondering two things.

First, why are the odd numbers coming before the even numbers? After all, the key value seems to be telling the sorted function to prioritize evens by using the mod operator in x % 2 == 0.

Second, why are the even numbers still out of order? 2 comes before 6, right?

By analyzing this result, we'll learn something deeper about how the 'key' argument really works, especially in conjunction with the anonymous lambda function.

Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:

Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.

We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.

So what does the example using a modulo return? A boolean value: True == 1, False == 0. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.

[3, 6, 3, 2, 4, 8, 23] becomes [0, 1, 0, 1, 1, 1, 0]

Now we're getting somewhere. What do you get when you sort the transformed list?

[0, 0, 0, 1, 1, 1, 1]

Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - it is because sorting only happens once! Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even numbers from low to high, those values remain in their original order relative to one another.

The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?

Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.

So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?

That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.

Lets try and predict what happens when I run the following code.

In [9]: mylist = [(3, 5, 8), (6, 2, 8), (2, 9, 4), (6, 8, 5)]
In[10]: sorted(mylist, key=lambda x: x[1])

My sorted call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, 'for each element x in mylist, return the second index of that element, then sort all of the elements of the original list mylist by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple using the lambda function.

The pointer that will be used to sort would be:

[5, 2, 9, 8] # the second element of each tuple

Sorting this pointer list returns:

[2, 5, 8, 9]

Applying this to mylist, we get:

Out[10]: [(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]
# Notice the sorted pointer list is the same as the second index of each tuple in this final list

Run that code, and you'll find that this is the order. Try sorting a list of integers using this key function and you'll find that the code breaks (why? Because you cannot index an integer of course).

This was a long winded explanation, but I hope this helps to sort your intuition on the use of lambda functions - as the key argument in sorted(), and beyond.

2 of 10
207

key is a function that will be called to transform the collection's items before they are compared. The parameter passed to key must be something that is callable.

The use of lambda creates an anonymous function (which is callable). In the case of sorted the callable only takes one parameters. Python's lambda is pretty simple. It can only do and return one thing really.

The syntax of lambda is the word lambda followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while, for, if and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.

We can compare the use of lambda with that of def to create a function.

adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2

lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.

variable is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.

🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί how does key argument in sorted() works with lambda function
r/learnpython on Reddit: how does key argument in sorted() works with lambda function
January 14, 2023 -

i was practicing a question where you have to sort an array by frequency of its elements and if the frequency is same then sort the elements themselves in reverse.

This was the fastest solution someone did:

def frequencySort(self, nums: List[int]) -> List[int]:
    num_freq = {}
    for num in nums:
        if num not in num_freq:
            num_freq[num] = 1
        else:
            num_freq[num] += 1
    nums.sort(key=lambda x: (num_freq[x], -x))
    return nums
#example 1
#input:  [2,3,1,3,2]
#output: [1,3,3,2,2]
#'2' and '3' both have a frequency of 2, so they are sorted in decreasing order.

#example 2
#input:  [-1,1,-6,4,5,-6,1,4,1]
#output: [5,-1,4,4,-6,-6,1,1,1]

I know how keys and lambda functions work but in this case i cant seem to figure out how its working. I tried using google and official docs but all the examples are basic.

🌐
Learn by Example
learnbyexample.github.io β€Ί tips β€Ί python-tip-33
Python tip 33: sorting iterables based on multiple conditions
# descending order based on the number of words # ascending alphabetic order for items with the same number of words >>> sorted(books, key=lambda b: (-b.count(' '), b)) ['The Weirkey Chronicles', 'Mage Errant', 'Cradle', 'Mistborn', 'Piranesi'] # reverse the above result >>> sorted(books, key=lambda b: (-b.count(' '), b), reverse=True) ['Piranesi', 'Mistborn', 'Cradle', 'Mage Errant', 'The Weirkey Chronicles'] See also docs.python HOWTOs: Sorting.