Python sort ExamplesSort elements: sort a list, a dictionary and use the sorted method with keys.
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.
Sorting things. 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 example. Let 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().
Result 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)
[-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.
Python program that uses reverse on list
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]
Sorted, reversed. These are views that transform lists without modifying them. Here, we apply the sorted() view and then the reversed() view and print the results.
Info We iterate over the reversed view with a for-loop. Reversed returns an iterator, not a list.
Tip You can 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)
1000 333 22 0 -22
Sorted, arguments. 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.
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)
lavender yellow blue red
Sort dictionary. How 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.
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])
chair 2 desk 4 table 1
Error. 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.
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'
Objects. 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.
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)
Bird, weight = 5 Bird, weight = 10 Bird, weight = 200
String chars. We 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.
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)
Benchmark, sorted. 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.
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())
1389905688.967582 1389905691.0347 Call sort(), reverse(): 2.07 s 1389905693.901864 Call sorted(), reversed(): 2.87 s
Custom. 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.
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
Usually the fastest and simplest way to deal with data is not to sort it. But often we need to sort. It helps organize data in memory and is helpful for writing data to a file.
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.
© 2007-2022 sam allen.
see site info on the changelog.