Lambda expression in Python to rearrange positive and negative numbers

PythonServer Side ProgrammingProgramming

In this article, we will learn about using lambda expressions that will take an input array of positive and negative integers. We compute two separate arrays one containing negative numbers and other containing positive numbers.

Here we define a Rearrange() function that accepts only one argument i.e. array of integers. The function returns both arrays merged together with each type on different sides of the array.

Now let’s see the code to understand it better.

Example

def Rearrange(arr):
# First lambda expression returns a list of negative numbers in arr.
# Second lambda expression returns a list of positive numbers in arr.
arr_neg=[x for x in arr if x < 0]
arr_pos=[x for x in arr if x >= 0]
return arr_neg+ arr_pos

# Driver function
if __name__ == "__main__":
   arr = [19,-56,3,-1,-45,-23,45,89,90]
   print (Rearrange(arr))

Output

[-56, -1, -45, -23, 19, 3, 45, 89, 90]

Conclusion

In this article, we learned how to implement lambda expressions to rearrange positive and negative integers in the input array.

raja
Published on 07-Aug-2019 11:47:48
Advertisements