python list sorted code example

Example 1: sorted list python

sorted(iterable, key=None, reverse=False)

type(sorted(iterable, key=None, reverse=False)) = list

Example 2: python sort comparator

sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Example 3: 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]

Example 4: pyhton built in sort

arr = [ 1, 3, 2]
arr.sort()

Example 5: sorted python

var = sorted(old_var)

Example 6: sort list in python

List_name.sort()
This will sort the given list in ascending order.