liveBook · Manning

Sorted

As explained in Python Workout: 50 ten-minute exercises

sorted is a Python built-in function that returns the elements of an iterable in sorted order as a new list.

Need to put items into order without changing the original iterable? Python’s built-in sorted function accepts any iterable and returns its elements in sorted order as a new list. With a string, it sorts individual characters by Unicode order, so converting the result back to text requires str.join. section 2.18 section 2.21

Sort characters, then rebuild a string

word = 'python'\ncharacters = sorted(word)\nprint(characters) # ['h', 'n', 'o', 'p', 't', 'y']\nprint(''.join(characters)) # hnopty\n\nThe sorting step produces a list; the empty string supplies the glue that joins its characters into a new string. section 2.18

Use sorted with different iterable types and ordering rules:

  • Sort lists and tuples directly; sorted always returns a list, even when the input is a tuple. section 2.21 section 3.26
  • Pass a function to key when the natural order is not enough. Python calls that function once per element and orders by its result. section 3.26 section 3.11
  • Apply key to practical tasks such as sorting names by last name and first name, numbers by absolute value, or words by vowel count. section 3.11 section 3.15
PEOPLE = [{'first':'Reuven', 'last':'Lerner',
   'email':'reuven@lerner.co.il'},
{'first':'Donald', 'last':'Trump',
   'email':'president@whitehouse.gov'},
{'first':'Vladimir', 'last':'Putin',
   'email':'president@kremvax.ru'}
]

Use the phone-book records to practice returning dictionaries ordered by last name and then first name with sorted and key. section 3.11

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains returned-list behavior and key-based ordering with exercises, but stops short of sorting algorithm internals.
Examples
Demonstrates sorted characters, alphabetized names, phone-book dictionaries, database-style tuples, and derived ordering criteria.
What it assumes
Assumes familiarity with Python sequences and functions while reinforcing that strings are iterable sequences and functions can be passed as arguments.
What you can do after
Apply it via Python’s built-in sorted to order iterable data and design custom key functions for multi-field or derived criteria.
How it connects
Connects sorted with iterables, strings, lists, tuples, dictionaries, str.join, str.split, key functions, lambda, and operator.itemgetter.

Also explained in

Compare how 5 books explain sorted →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.