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




