xxxxxxxxxx
my_list = [11, 3, 7, 5, 2]
my_list.sort() # sorting the list in ascending order
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
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
# For a dataframe
sorted_df = df.sort_values(by=['cat_col', 'num_col'], ascending=[True, False])
each_group_top = sorted_df.groupby(['cat_col'])['num_col'].head(1) # top row of each category column
# Sorted provides more way of customization... example with networkx
sorted(nx.find_cliques(G), key=lambda x:len(x))[-1]
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
# 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
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)