Sort
To perform sorting in Python, we use built-in methods. We use sort and sorted()
. The sorted()
built-in returns a view (not a list) that is ordered.
We can sort from low to high (ascending) or the opposite (descending). We can even sort based on a property or function call result.
Sort
exampleLet us first reorder a list of integers. To order a list's elements from lowest to highest (starting with negative numbers, moving to positive ones), we call sort()
.
sort()
call.# Contains unsorted, positive and negative integers. elements = [100, 200, 0, -100] # Sort from low to high. elements.sort() print(elements)[-100, 0, 100, 200]
Reverse
This operation inverts the order of the elements in a list. With reverse()
we modify the list in-place—no assignment is needed.
values = [100, 200, 300] print("BEFORE: ", values) # Call reverse and print the changed list. values.reverse() print("REVERSE:", values)BEFORE: [100, 200, 300] REVERSE: [300, 200, 100]
These are views that transform lists without modifying them. Here, we apply the sorted()
view and then the reversed()
view and print the results.
for
-loop. Reversed returns an iterator, not a list.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)1000 333 22 0 -22
This built-in can receive more than one argument. The first is the collection we want to sort. But we also can specify a key function.
# 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)lavender yellow blue red
Sort
dictionaryHow can you sort the keys in a dictionary? First you must acquire a list of the keys using the keys()
method. Then, you can use the sorted built-in to order those 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])chair 2 desk 4 table 1
An error will occur if you try to sort the result of the keys method. This is because keys does not return a list—it returns a dict_keys
object. We would need to use sorted()
here.
AttributeError: 'dict_keys' object has no attribute 'sort'
A list of class
instances (objects) can be sorted. Here we introduce the Bird class
. Each Bird has a weight. And the repr method returns a string
representation of each object.
sort()
method with a lambda "key" argument. The lambda selects the key that each Bird is sorted upon.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)Bird, weight = 5 Bird, weight = 10 Bird, weight = 200
String
charsWe can sort the characters in a string
. We first convert the string
to a list of characters with a list comprehension. Then, after sort()
, we join the chars together.
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)abot
I benchmarked the sort()
and reverse()
methods, and compare them to the sorted()
and reversed()
views. I found that the sort and reverse methods were more efficient here.
sort()
and reverse()
methods. It loops over the returned elements.sorted()
and reversed()
methods, and loop over the returned collections.sorted()
and reversed()
views is not always a performance advantage.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())1389905688.967582 1389905691.0347 Call sort(), reverse(): 2.07 s 1389905693.901864 Call sorted(), reversed(): 2.87 s
The data structures we construct before sorting are important. For example, building a list of tuples, and then sorting on an item in each tuple, is effective.
In Python, we can directly use sort, or use the sorted()
view. Where possible, using sort()
is faster because it copies less. But often the simplest solution is preferred.