Write a python program to sort list with sorted & lambda

Write a python program to sort list with sorted & lambda

Program
The sorted() function is a high-order function because it takes another function as a parameter. Here, we create a lambda function that is then passed as an argument to the sorted() function key parameter. By using a negative index [-1], we are telling the sorted() function to sort the list in descending order.
def myfun():
    list1 = ['Sateesh', 'Kumar', 'Siva']
    a = lambda x: x[-1]
    y = sorted(list1, key=a)
    print(y)
                 
if __name__=="__main__":
    myfun()


Output:

['Siva', 'Sateesh', 'Kumar']


Program
To sort the list in ascending order, we can just change the index to [:1]. See below:
def myfun():
    list1 = ['Sateesh', 'Kumar', 'Siva']
    a = lambda x: x[:1]
    y = sorted(list1, key=a)
    print(y)
                 
if __name__=="__main__":
    myfun()



Output:

['Kumar', 'Sateesh', 'Siva']


Program
Another easy way to sort the list in ascending order would be to use just the sorted() function. By default, it sorts an iterable in ascending order. Since the key parameter is optional, we just leave it out.
def myfun():
    list1 = ['Sateesh', 'Kumar', 'Siva']
    list2 = sorted(list1)
    print(list2)
                 
if __name__=="__main__":
    myfun()



Output:

['Kumar', 'Sateesh', 'Siva']



More Questions


50 . Write a python program to sort list with sorted & lambda
51 . Write a python program to access news using python
52 . Write a python program to print lowercase names
53 . Write a python program to Find Index Using Enumerate
54 . Write a python program to checking if a string is empty or not ?
55 . Write a python program to merge nested lists ?
56 . Write a python program to Checking if a File Exists or Not ?
57 . Write a python program to convert uppercase strings and we want to convert them into lowercase strings and remove duplicates ?
58 . Write a python program to display list of numbers and we want to return all the numbers from the list that are divisible by 2 and remove duplicates at the same time.
59 . Write a python program to calculate average using python *args ?
60 . Write a Python program to find the area of a triangle.



For latest job updates join Telegram Channel: https://t.me/sateeshm