- Related Questions & Answers
- Lambda expression in Python to rearrange positive and negative numbers
- 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
- Reversing negative and positive numbers in JavaScript
- Implement Bubble sort with negative and positive numbers – JavaScript?
- Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
- Sum a negative number (negative and positive digits) - JavaScript
- Python program to print negative numbers in a list
- Python Program to Check if a Number is Positive, Negative or 0
- Map function and Lambda expression in Python to replace characters
- How to print positive and negative infinity values in JavaScript?
- How to generate prime numbers using lambda expression in Java?
- Counting number of positive and negative votes in MySQL?
- Program to rearrange spaces between words in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

Advertisements