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
Syntax
a.sort()
Parameters
a
fn
Related .insert()
.pop()
.append()
.index()
sorted()
Updated on Wed Jan 18 17:32:21 2017.
Creative Commons License