Puts a list in order.
Synopsis
items.sort()
items.sort(reverse=True)
sorted(items)
Description
items.sort() changes the list itself. sorted(items) leaves it alone and returns a new, sorted list.
Strings sort by character code, so capital letters come before lowercase ones.
Parameters
| Name | Meaning |
|---|---|
reverse |
True sorts from largest to smallest. Optional. |
Return value
sort returns None. sorted returns a new list.
Example
nums = [3, 1, 2]
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums)
words = ["banana", "Apple", "cherry"]
print(sorted(words))
print(words)
It prints:
[1, 2, 3]
[3, 2, 1]
['Apple', 'banana', 'cherry']
['banana', 'Apple', 'cherry']
Common mistake
items = [3, "a", 1]
items.sort()
Python stops with:
TypeError: '<' not supported between instances of 'str' and 'int'
Python cannot say whether a number comes before a string. Keep one type per list.
See also
Last updated 2 weeks ago