# sort() will change the original list into a sorted list
vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort()
# Output:
# ['a', 'e', 'i', 'o', 'u']
# sorted() will sort the list and return it while keeping the original
sortedVowels = sorted(vowels)
# Output:
# ['a', 'e', 'i', 'o', 'u']
Python .sort() / .sorted()
.sort() Sort modifies the list directly.
names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]
names.sort()
print(names)
# ['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']
.sort() also provides us the option to go in reverse easily.
Instead of sorting in ascending order, we can do so in descending order.
names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]
names.sort(reverse=True)
print(names)
# ['Xander', 'Willow', 'Giles', 'Buffy', 'Angel']
.sorted() generates a new list instead of modifying
one that already exists.
names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]
sorted_names = sorted(names)
print(sorted_names)
# ['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']
"""Sort in ascending and descending order"""
list_test = [2, 1, 5, 3, 4]
#ascending is by default for sort
#Time Complexity: O(nlogn)
list_test.sort()
#For descending order
#Time Complexity: O(nlogn)
list_test.sort(reverse=True)
#For user-define order
list_test.sort(key=..., reverse=...)
data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []
while data_list:
minimum = data_list[0] # arbitrary number in list
for x in data_list:
if x < minimum:
minimum = x
new_list.append(minimum)
data_list.remove(minimum)
print new_list
# Sort with an inner object
# Here it will sort with "book_no"
# [
# {
# "key": "book-key-1",
# "book_no": 1,
# "name": "My Book Name 1"
# },
# {
# "key": "book-key-2",
# "book_no": 2,
# "name": "My Book Name 2"
# }
# ]
def sortOnNumber(e):
return e['book_no']
@app.get('/getBooks')
def getBooks():
res = next(booksDb.fetch())
res.sort(key=sortOnNumber)
if res:
return res
raise HTTPException(404,"Not found")