Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Lambda expression in Python Program to rearrange positive and negative numbers
In this tutorial, we will write an anonymous function using lambda to rearrange positive and negative numbers in a list. The goal is to place all negative numbers first, followed by all positive numbers.
Algorithm
Let's see how to solve the problem step by step ?
1. Initialize a list with negative and positive numbers. 2. Write a lambda expression that takes a list as an argument. 2.1. Iterate over the list and get negative numbers 2.2. Same for positive numbers 2.3. Combine both using concatenation operator. 3. Return the resultant list.
Note − Use list comprehension to get negative and positive numbers.
Using Lambda Expression
Here's how to implement the solution using lambda with list comprehension ?
# initializing a list
arr = [3, 4, -2, -10, 23, 20, -44, 1, -23]
# lambda expression to rearrange numbers
rearrange_numbers = lambda arr: [x for x in arr if x < 0] + [x for x in arr if x >= 0]
# rearranging the array
new_arr = rearrange_numbers(arr)
# printing the resultant array
print("Original array:", arr)
print("Rearranged array:", new_arr)
Original array: [3, 4, -2, -10, 23, 20, -44, 1, -23] Rearranged array: [-2, -10, -44, -23, 3, 4, 23, 20, 1]
How It Works
The lambda function performs two operations ?
-
[x for x in arr if x < 0]− Creates a list of all negative numbers -
[x for x in arr if x >= 0]− Creates a list of all positive numbers (including zero) - The
+operator concatenates both lists
Alternative Approach with Regular Function
For comparison, here's the same logic using a regular function ?
def rearrange_numbers(arr):
negatives = [x for x in arr if x < 0]
positives = [x for x in arr if x >= 0]
return negatives + positives
# test with the same array
arr = [3, 4, -2, -10, 23, 20, -44, 1, -23]
result = rearrange_numbers(arr)
print("Result:", result)
Result: [-2, -10, -44, -23, 3, 4, 23, 20, 1]
Conclusion
Lambda functions provide a concise way to write short operations. In this case, the lambda expression efficiently rearranges numbers by separating negatives and positives using list comprehension and concatenation.
---