Example 1: how do i sort list in python
my_list = [9, 3, 1, 5, 88, 22, 99]
# sort in decreasing order
my_list = sorted(my_list, reverse=True)
print(my_list)
# sort in increasing order
my_list = sorted(my_list, reverse=False)
print(my_list)
# another way to sort using built-in methods
my_list.sort(reverse=True)
print(my_list)
# sort again using slice indexes
print(my_list[::-1])
# Output
# [99, 88, 22, 9, 5, 3, 1]
# [1, 3, 5, 9, 22, 88, 99]
# [99, 88, 22, 9, 5, 3, 1]
# [1, 3, 5, 9, 22, 88, 99]
Example 2: python sort list in reverse
#1 Changes list
list.sort(reverse=True)
#2 Returns sorted list
sorted(list, reverse=True)
Example 3: python sort list
# 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']
Example 4: how to sort a list in python
l=[1,3,2,5]
l= sorted(l)
print(l)
#output=[1, 2, 3, 5]
#or reverse the order:
l=[1,3,2,5]
l= sorted(l,reverse=True)
print(l)
#output=[5, 3, 2, 1]
Example 5: sort function
var vehicules= [
{ nom: "Peugeot 208 1,2l PureTech", img:"208.png" , co2:108 },
{ nom: "Peugeot 5008 2.0 BlueHDi 150", img:"5008.png" , co2: 118 },
{ nom: "Golf GTI", img:"golfgti.png" , co2:148 },
{ nom: "Renault Clio 0.9 TCe 90", img:"clio.jpg" , co2:114 },
{ nom: "Audi A4 2.0 TDI 190", img:"a4.png" , co2: 111},
{ nom: "BMW Serie 2 Tourer 220d", img:"serie2tourer.png" , co2:124 },
{ nom: "Audi SQ7", img:"sq7.png" , co2:198 },
{ nom: "Audi TTS", img:"tts.png" , co2:159 },
];
vehicules.sort(function (a, b) {
return a.co2 - b.co2;
});
vehicules.forEach(function(v) {
console.log(v.nom+" avec "+v.co2+" g de CO2/km");
});
Example 6: list sort python
>>> names = ['Harry', 'Suzy', 'Al', 'Mark']
>>> sorted(names)
['Al', 'Harry', 'Mark', 'Suzy']
>>> sorted(names, reverse=True)
['Suzy', 'Mark', 'Harry', 'Al']