- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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.
See the code below if you stuck at any point.
# 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)
If you execute the above program, then you will get the following output.
[-2, -10, -44, -23, 3, 4, 23, 20, 1]
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.
- Lambda expression in Python to rearrange positive and negative numbers
- Rearrange positive and negative numbers using inbuilt sort function in C++
- Rearrange positive and negative numbers with constant extra space in C++
- Python program to count positive and negative numbers in a list
- Count positive and negative numbers in a list in Python program
- Java Program to convert positive int to negative and negative to positive
- Rearrange positive and negative numbers in O(n) time and O(1) extra space in C++
- Golang Program to Print the Sum of all the Positive Numbers and Negative Numbers in a List
- Python - Sum negative and positive values using GroupBy in Pandas
- Rearrange array in alternating positive & negative items with O(1) extra space in C++
- Map function and Lambda expression in Python to replace characters