Python | Rearrange Positive and Negative Elements
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.
# Python3 code to demonstrate working of # Sort while keeping Positive elements before negatives # using sorted() + lambda # initialize list test_list = [ 4 , - 8 , - 6 , 3 , - 5 , 8 , 10 , 5 , - 19 ] # printing original list print ( "The original list is : " + str (test_list)) # Sort while keeping Positive elements before negatives # using sorted() + lambda res = sorted (test_list, key = lambda i: 0 if i = = 0 else - 1 / i) # printing result print ( "Result after performing sort operation : " + str (res)) |
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]
Recommended Posts:
- Lambda expression in Python to rearrange positive and negative numbers
- Python program to count positive and negative numbers in a list
- Python | Counting sign change in list containing Positive and Negative Integers
- Python | Get positive elements from given list of lists
- Program to check if a number is Positive, Negative, Odd, Even, Zero
- numpy.negative() in Python
- Python | Filter the negative values from given dictionary
- Python | Replace negative value with zero in numpy array
- Python program to print all negative numbers in a range
- Python program to print negative numbers in a list
- Python program to print all positive numbers in a range
- Python program to print positive numbers in a list
- Reverse bits of a positive integer number in Python
- Python | Index of Non-Zero elements in Python list
- Python | Get Top N elements from Records
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.