Syntax behind sortedkeylambda ...
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
The expression sorted(data, key=lambda x: ...) is one of those Python idioms that feels cryptic until you know what part each token plays. Once you break it apart, it is just sorted asking for a helper function and lambda providing that helper inline.
Core Sections
What sorted expects
sorted takes an iterable and returns a new list in sorted order. If you do not provide a key, Python compares the items directly. If you do provide key=..., Python first computes a comparison value for each item and sorts using those values instead.
That works because integers already know how to compare themselves. With tuples, dictionaries, or objects, you often need to tell Python which part matters for ordering.
Reading key=lambda item: item[1]
Take this common example:
Read it from left to right:
- '
sorted(records, ...)means "return a new sorted list."' - '
key=means "sort by a derived value."' - '
lambda item: item[1]means "for each item, return its second element."'
So Python does not sort the tuples by tuple rules here. It asks the lambda for a key for each tuple and sorts by those keys.
lambda is just a tiny unnamed function
If lambda syntax feels compressed, translate it into a normal function. The behavior is the same.
This is the simplest mental model: lambda item: item[1] is an inline version of a one-line function. Python uses it when the helper is short enough that naming it would add ceremony rather than clarity.
Common patterns for sort keys
Sort keys are useful far beyond tuples. You can sort case-insensitively:
You can sort dictionaries by one field:
You can also sort by multiple criteria by returning a tuple key:
Python compares tuple keys lexicographically, so it sorts by item[1] first and uses item[0] as a tiebreaker.
sorted versus .sort()
Another part of the syntax that trips people up is whether the original list changes. sorted(...) always returns a new list, leaving the original iterable unchanged. .sort(...) sorts an existing list in place.
Use sorted when you need a new list or when the source is not already a list. Use .sort() when mutating the original list is acceptable.
When not to use lambda
Inline lambdas are convenient, but they should stay small. If the key logic contains several conditions, a fallback lookup, or normalization steps that are meaningful on their own, give the function a name. Python code stays easier to maintain when the sort rule reads like a decision, not like punctuation.
For very common cases, the operator module is even cleaner:
itemgetter(1) communicates intent immediately for tuple-like data.
Common Pitfalls
- Assuming the key function compares items directly. It only returns the value Python should compare.
- Forgetting that
sortedreturns a new list and does not mutate the original data. - Returning inconsistent types from the key function, such as strings for some items and integers for others.
- Writing a long, clever lambda when a named function or
itemgetterwould be clearer. - Overlooking tuple keys when you need primary and secondary sort criteria.
Summary
- '
sorted(..., key=...)sorts by a derived value rather than by the raw item.' - '
lambda item: item[1]means "take an item and return its second element."' - A lambda here is just a short unnamed helper function.
- Tuple keys let you express multi-column sorts cleanly.
- Use
sorted,.sort(),lambda, or helper functions based on readability and whether you want a new list or an in-place sort.
Related reading
- Syntax error on print with Python 3
- SyntaxError invalid syntax in running python kafka code
- SyntaxError Non-ASCII character ... or SyntaxError Non-UTF-8 code starting with ... trying to use non-ASCII text in a Python script
- Take multiple lists into dataframe
- Take the content of a list and append it to another list
- Temporary queue made in Celery
- Tensor object has no attribute keras_shape
- ''Tensor'' object has no attribute ''lower''
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.