Name

.sort()

Examples
numbers = [10.6, -14, 1000, 3, 7]
numbers.sort()
print(numbers) # Prints [-14, 3, 7, 10.6, 1000]

inventory = ["wallet", "mummy wrap", "ancient map", "crowbar"]
inventory.sort()
print(inventory) # Prints ['ancient map', 'crowbar', 'mummy wrap', 'wallet']

# Use reverse=True to sort list in reverse
inventory.sort(reverse=True)
print(inventory) # Prints ['wallet', 'mummy wrap', 'crowbar', 'ancient map']
# sort() is, by default, case insensitive
items = ["Abacus", "abacus", "Zwieback", "zwieback"]
items.sort()
print(items) # Prints ['Abacus', 'Zwieback', 'abacus', 'zwieback']

# Pass a function as an argument to sort() to apply a transformation to
# items before sorting
def case_insensitive(item):
  return item.lower()
items.sort(key=case_insensitive)
print(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"]
items.sort(key=len)
print(items) # Prints ['egg', 'desk', 'flask', 'buffalo', 'charcoal']

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

Description Sort the elements of a list in place. Numbers are sorted by their value, and strings are sorted in (case-sensitive) alphabetical order. If the keyword argument reverse is given and set to True, the list is sorted in reverse.

An optional keyword parameter key specifies a function that will be called for each item of the list before comparing it in the sorting process. This function takes a single parameter and should return the value that Python should use for the specified value when sorting the list. You can use this functionality to easily build (as in the example above) a case-insensitive sort.
Syntax
a.sort()
Parameters
athe list to sort
fna function, called automatically for each list element
Related .insert()
.pop()
.append()
.index()
sorted()

Updated on Mon Sep 21 15:53:25 2020.

If you see any errors or have comments, please let us know.