Sometimes, while working with Python lists, we can have a problem in which we need to perform a sort in list. There are many variations of sorting that might be required to perform. Once such variation can be to sort elements of list, but keeping in mind, positive elements appear before negative elements. Let’s discuss a way in which this task can be performed.
Method : Using
sorted() + lambda
This task can be performed using combination of above functions. In this, the logic we apply is computing inverse and negative of each number and then perform the sort using
sorted(). The inversion makes sure that larger magnitude elements occur at middle and smaller at ends ( hill arrangement ) and negative takes care of making positives occur before negatives.
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19] Result after performing sort operation : [3, 4, 5, 8, 10, -19, -8, -6, -5]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course