python sort by list code example

Example 1: python sort a list by a custom order

# Example usage:
list_to_sort = [('U', 23), ('R', 42), ('L', 17, 'D')]
custom_sort_order = ['R', 'D', 'L', 'U']
sorted(list_to_sort, key=lambda list_to_sort: custom_sort_order.index(list_to_sort[0]))
# Where 0 is the tuple index to use for sorting by custom order
--> [('R', 42), ('L', 17, 'D'), ('U', 23)]

Example 2: pythonn sort example

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

Example 3: sort in python'

arr = [1,4,2,7,5,6]
#sort in ascending order
arr = arr.sort() 

#sort in descending order
arr = arr.sort(reverse = True)

Example 4: python sort

nums = [4,8,5,2,1]
#1 sorted() (Returns sorted list)
sorted_nums = sorted(nums)
print(sorted_nums)#[1,2,4,5,8]
print(nums)#[4,8,5,2,1]

#2 .sort() (Changes original list)
nums.sort()
print(nums)#[1,2,4,5,8]