Name

sorted()

Examples
numbers = [3.4, 3.6, 2, 0, 7.1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Prints [0, 2, 3.4, 3.6, 7.1]

# original list left unchanged
print(numbers) # Prints [3.4, 3.6, 2, 0, 7.1]
animals = ["deer", "elephant", "bear", "aardvark", "cat"]
sorted_animals = sorted(animals)
print(sorted_animals) # Prints ['aardvark', 'bear', 'cat', 'deer', 'elephant']

# reverse=True reverses the order of the sort
rev_animals = sorted(animals, reverse=True)
print(rev_animals) # Prints ['elephant', 'deer', 'cat', 'bear', 'aardvark']

# sorted() lets you sort any iterable, not just lists!
word = "parabolas"
sorted_word = sorted(word)
print(sorted_word) # Prints ['a', 'a', 'a', 'b', 'l', 'o', 'p', 'r', 's']
# sorted() is, by default, case insensitive
items = ["Abacus", "abacus", "Zwieback", "zwieback"]
sorted_items = sorted(items)
print(sorted_items) # Prints ['Abacus', 'Zwieback', 'abacus', 'zwieback']

# Pass your own function as an argument to sort() to apply a transformation to
# items before sorting
def case_insensitive(item):
  return item.lower()
sorted_items = sorted(items, key=case_insensitive)
print(sorted_items) # Prints ['Abacus', 'abacus', 'Zwieback', 'zwieback']

# sort list of strings by their length, using the built-in function len()
# as the key parameter
items = ["buffalo", "charcoal", "desk", "egg", "flask"]
sorted_items = sorted(items, key=len)
print(sorted_items) # Prints ['egg', 'desk', 'flask', 'buffalo', 'charcoal']

# You can use the "key" parameter and the "reverse" parameter in the same
# call to sort!
sorted_items = sorted(items, key=len, reverse=True)
print(sorted_items) # Prints ['charcoal', 'buffalo', 'flask', 'desk', 'egg']

Description
Syntax
sorted(iterable)
sorted(iterable, reverse=True)
sorted(iterable, key=fn)
Parameters
list
count
Related .reverse()
Updated on Wed Jan 18 17:32:21 2017.
Creative Commons License