How to sort a list of strings with sorted() built-in function in Python

The aim of this page📝 is to use a lambda function passed into a key keyword parameter of a built-in sorted() function to sort a list of strings. I specifically need to sort a bunch of HTTP endpoints containing an integer at the end.

Pavol Kutaj
2 min readAug 18, 2023
  • sorted builtin is used for sorting iterable series
  • the optional key keyword argument must be a callable and it provides a key according to which the list should be sorted
sorted(<iterable>,key=<callable>)
  • the key works as a mapping function
def sort_names(names):
return sorted(names, key=lambda name: name.split()[-1])

""" PYTEST """
def test_sort_names():
input = ["alan turing", "bill gates"]
result = sort_names(input)
assert result == ["bill gates", "alan turing"]
  • that lambda name: name.split()[-1] does is a mapping function to transform individual list items+
  • …and sorting will be done based on the transformed values, in the example above you are sorting
"turing", "gates" ⟹ "gates", "turing"
  • another usecase may be that of sorting a list of endpoints with semver versioning at the end — say I am getting these
["com.example-company/foobar_schema/jsonschema/1-0-1", 
"com.example-company/foobar_schema/jsonschema/1-0-2",
"com.example-company/foobar_schema/jsonschema/1-0-0"]
  • For some reason, like running a request containing the version in a given order, I must sort the string with the patch version
# ENDPOINTS TO SORT
>>> vers = ["com.example-company/foobar_schema/jsonschema/1-0-1",
... "com.example-company/foobar_schema/jsonschema/1-0-2",
... "com.example-company/foobar_schema/jsonschema/1-0-0"]

# 'key' MUST BE A KEYWORD ARG!
>>> sorted(vers, lambda vers: int(vers[-1]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sorted expected 1 argument, got 2

# sorted() AS EXPECTED
>>> sorted(vers, key=lambda vers: int(vers[-1]))
['com.example-company/foobar_schema/jsonschema/1-0-0', 'com.example-company/foobar_schema/jsonschema/1-0-1', 'com.example-company/foobar_schema/jsonschema/1-0-2']

LINKS

--

--

No responses yet