sorted() accepts an iterable and returns a new list in sorted order, leaving the original collection unchanged. It is useful when the ordered result matters but the input must remain available in its original order. section 3.3.7
Keep these behaviors distinct:
- sorted(items) produces a new list; items.sort() sorts the existing list in place and returns None. section 3.3.7
- sorted([4, 2, 10, 3, 1]) returns [1, 2, 3, 4, 10], while mixed strings and numbers raise a TypeError. section 3.3.7
- Sorting a set creates a list with a consistent order, which supports reproducible calls to random.sample(). section 20.1.6
Preserve the input while sorting
>>> items = ['soda', 'sammiches', 'chips', 'ice cream'] >>> sorted_items = sorted(items) >>> sorted_items ['chips', 'ice cream', 'sammiches', 'soda'] >>> items ['soda', 'sammiches', 'chips', 'ice cream'] A command-line program can apply this behavior when the user supplies a --sorted Boolean flag. A password generator can similarly use words = sorted(words) before random.sample(words, args.num_words). section 3.3.7 section 3.4.1 section 20.1.6
>>> items = ['soda', 'sammiches', 'chips', 'ice cream'] >>> sorted(items) ['chips', 'ice cream', 'sammiches', 'soda']
Inspect the REPL comparison between sorted(items) and the unchanged original list. section 3.3.7




