# 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']
# List of Integers
numbers = [1, 3, 4, 2]
# Sorting list of Integers
numbers.sort()
print(numbers)
# List of Floating point numbers
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]
# Sorting list of Floating point numbers
decimalnumber.sort()
print(decimalnumber)
# List of strings
words = ["Geeks", "For", "Geeks"]
# Sorting list of strings
words.sort()
print(words)
gList = [ "Rocket League", "Valorant", "Grand Theft Autu 5"]
gList.sort()
# OUTPUT --> ['Grand Theft Auto 5', 'Rocket League', 'Valorant']
# It sorts the list according to their names
words = ["apple","pear","red"]
numbers = [4,2,7,5]
#Parameters:
#key: changes how it sorts the list, For Example: letters.sort(key=len) Sorts by length
#Reverse: Default: sorts in ascending order, if Reverse is True: sorts descending order
words.sort(key=len)
>["red","pear","apple"]
numbers.sort(reverse=True)
>[7,5,4,2]
#sort: changes the list so it is sorted
#sorted: returns the sorted list
a=[2,2,4,1]
b=a
a.sort()
// a now points to object [1,2,2,4]
c=sorted(b)
//c and b also points to [1,2,2,4]
// sort works on array only but sorted also on strings but return array of char
s="sjndk"
print(sorted(s))
// prints ['d', 'j', 'k', 'n', 's']
// sorted also works on list of strings(sorts alphabetically)
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")