Lambda expression in Python Program to rearrange positive and negative numbers


In this tutorial, we are going to write an anonymous function using lambda to rearrange positive and negative number in a list. We need the pick the negative numbers and then positive numbers from a list to create a new one.

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 the 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 concatination operator.
3. Return the resultant list.

Note - Use the list comprehension to get negative and positive numbers.

Example

See the code below if you stuck at any point.

 Live Demo

# initializing a list
arr = [3, 4, -2, -10, 23, 20, -44, 1, -23]
# lambda expression
rearrange_numbers = lambda arr: [x for x in arr if x < 0] + [x for x in arr if x >= 0]
# rearranging the arr
new_arr = rearrange_numbers(arr)
# printing the resultant array
print(new_arr)

Output

If you execute the above program, then you will get the following output.

[-2, -10, -44, -23, 3, 4, 23, 20, 1]

Conclusion

Lambda functions are great for a small operation that need to be perform many times in a program. If you have any doubts regarding the tutorial, mention them in the comment section.

Updated on: 24-Apr-2020

509 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements