liveBook · Manning

Sorted

As explained in Get Programming: Learn to code with Python

A Python built-in function that returns a new list containing the items of an iterable in sorted order.

sorted returns a new list with an iterable’s items in sorted order. Unlike list.sort(), it leaves the original list unchanged. section 28.2

Keep the original list

kid_ages = [2, 1, 4] sorted_ages = sorted(kid_ages) sorted_ages # [1, 2, 4] kid_ages # [2, 1, 4] The result goes into sorted_ages, while kid_ages stays in its original order. section 28.2

Choose the operation that matches your goal:

  • Use sorted(values) when you need a sorted copy. section 28.2
  • Use values.sort() when changing the existing list is acceptable. section 28.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Demonstrates the return value and contrasts copying with in-place sorting, without discussing sorting internals.
Examples
Uses a kid_ages list to show sorted output alongside the unchanged original.
What it assumes
Assumes familiarity with lists, variables, and changing mutable objects.
What you can do after
Apply sorted to create an ordered list without modifying the source list.
How it connects
Connects sorted with list.sort, list copying, and mutable objects.

Also explained in

Compare how 5 books explain sorted →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.