xxxxxxxxxx
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]
xxxxxxxxxx
# 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']
xxxxxxxxxx
# example list, product name and prices
price_data = [['product 1', 320.0],
['product 2', 4387.0],
['product 3', 2491.0]]
# sort by price
print(sorted(price_data, key=lambda price: price[1]))
xxxxxxxxxx
l = [64, 25, 12, 22, 11, 1,2,44,3,122, 23, 34]
for i in range(len(l)):
for j in range(i + 1, len(l)):
if l[i] > l[j]:
l[i], l[j] = l[j], l[i]
print l
xxxxxxxxxx
# define a list
my_list = [3, 1, 4, 2]
# sort the list
sorted_list = sorted(my_list)
print(sorted_list) # print as [1, 2, 3, 4]
# sort the list in place
my_list.sort()
print(my_list) # print as [1, 2, 3, 4]
# sort the list in descending order
sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # print as [4, 3, 2, 1]
# sort the list in place in descending order
my_list.sort(reverse=True)
print(my_list) # print as [4, 3, 2, 1]
xxxxxxxxxx
prime_numbers = [11, 3, 7, 5, 2]
# sorting the list in ascending order
prime_numbers.sort()
print(prime_numbers)
# Output: [2, 3, 5, 7, 11]