C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The list is sorted in-place. Nothing needs to be assigned to the sort() call.
Python program that sorts list
# Contains unsorted, positive and negative integers.
elements = [100, 200, 0, -100]
# Sort from low to high.
elements.sort()
print(elements)
Output
[-100, 0, 100, 200]
Then: We iterate over the reversed view with a for-loop. Reversed returns an iterator, not a list.
Warning: You can actually apply a reversed sort directly with the sorted keyword. Simply set the "reverse" argument to True.
Python program that uses reversed, sorted
elements = [22, 333, 0, -22, 1000]
# Use a reversed, sorted view: a descending view.
view = reversed(sorted(elements))
# Display our results.
for element in view:
print(element)
Output
1000
333
22
0
-22
Key: This is a function that receives an element, and returns a value that is used to sort.
Tip: A lambda expression may be used for the key argument. Here we receive an argument with name "color," and return its length.
Reverse: We can specify that the collection is to be sorted in descending order (from high to low) by setting reverse to true.
Python program that uses sorted, key, reverse
# An array of color names.
colors = ["blue", "lavender", "red", "yellow"]
# Sort colors by length, in reverse (descending) order.
for color in sorted(colors, key=lambda color: len(color), reverse=True):
print(color)
Output
lavender
yellow
blue
red
Note: This approach requires a lookup to get the values from the sorted key view. Another approach may be faster.
Python program that sorts dictionary keys
# A dictionary with three pairs.
furniture = {"table": 1, "chair": 2, "desk": 4}
# Get sorted view of the keys.
s = sorted(furniture.keys())
# Display the sorted keys.
for key in s:
print(key, furniture[key])
Output
chair 2
desk 4
table 1
So: We have to use sorted() here to avoid further conversions. We are not actually dealing with lists.
However: If the program has to repeatedly get the keys and sort them, using a cached list of the sorted keys would likely be faster.
Error from calling sort on keys:
AttributeError: 'dict_keys' object has no attribute 'sort'
Append: We append three new Bird objects to our list. The Birds are not ordered by their weights when we add them.
Sort: We use the sort() method with a lambda "key" argument. The lambda selects the key that each Bird is sorted upon.
Finally: We display the sorted list of birds. This approach can be used with any object type.
Python program that sorts list of objects
class Bird:
def __init__(self, weight):
self.__weight = weight
def weight(self):
return self.__weight
def __repr__(self):
return "Bird, weight = " + str(self.__weight)
# Create a list of Bird objects.
birds = []
birds.append(Bird(10))
birds.append(Bird(5))
birds.append(Bird(200))
# Sort the birds by their weights.
birds.sort(lambda b: b.weight())
# Display sorted birds.
for b in birds:
print(b)
Output
Bird, weight = 5
Bird, weight = 10
Bird, weight = 200
Python program that sorts string chars
value = "boat"
# Get list comprehension of characters and sort the list.
list = [c for c in value]
list.sort()
# Join the characters together.
result = "".join(list)
print(result)
Output
abot
Version 1: This version of the code uses the sort() and reverse() methods. It loops over the returned elements.
Version 2: Here we use the sorted() and reversed() methods, and loop over the returned collections.
Result: We discover that using sorted() and reversed() views is not always a performance advantage.
Python program that benchmarks sorted, reversed
import time
data = ["carrot", "apple", "peach", "nectarine"]
print(time.time())
# Version 1: use sort and reverse.
i = 0
while i < 1000000:
v = 0
data.sort()
for element in data:
v += 1
data.reverse()
for element in data:
v += 1
i += 1
print(time.time())
# Version 2: use sorted and reversed.
i = 0
while i < 1000000:
v = 0
for element in sorted(data):
v += 1
for element in reversed(data):
v += 1
i += 1
print(time.time())
Output
1389905688.967582
1389905691.0347 Call sort(), reverse(): 2.07 s
1389905693.901864 Call sorted(), reversed(): 2.87 s
Files sizes: We sort files by their sizes. We store each file and its size to a tuple, and then append that tuple to a list.
Sort Files, Size