w3resource

Python: Rearrange positive and negative numbers in a given array using Lambda


12. Rearrange Pos/Neg Lambda

Write a Python program to rearrange positive and negative numbers in a given array using Lambda.

Sample Solution:

Python Code :

# Define a list 'array_nums' containing both positive and negative integers
array_nums = [-1, 2, -3, 5, 7, 8, 9, -10]

# Display a message indicating that the following output will show the original array
print("Original arrays:")
print(array_nums)  # Print the contents of 'array_nums'

# Use the 'sorted()' function to rearrange the elements in 'array_nums' based on a custom key
# The 'key' parameter uses a lambda function to sort the elements:
#   - It places positive numbers before negative numbers and zeros, maintaining their original order
#   - Zeros are placed at the front (index 0) of the sorted list
result = sorted(array_nums, key=lambda i: 0 if i == 0 else -1 / i)

# Display the rearranged array where positive numbers come before negative numbers and zeros
print("\nRearrange positive and negative numbers of the said array:")
print(result)  # Print the rearranged 'result' array.

Sample Output:

Original arrays:
[-1, 2, -3, 5, 7, 8, 9, -10]

Rearrange positive and negative numbers of the said array:
[2, 5, 7, 8, 9, -10, -3, -1]

For more Practice: Solve these Related Problems:

  • Write a Python program to rearrange an array so that all even numbers appear before the odd numbers using lambda.
  • Write a Python program to rearrange an array so that numbers divisible by 3 come first using lambda.
  • Write a Python program to rearrange an array such that prime numbers are positioned at the beginning using lambda.
  • Write a Python program to rearrange an array by alternating positive and negative numbers using lambda.

Go to:


Previous: Write a Python program to find intersection of two given arrays using Lambda.
Next: Write a Python program to count the even, odd numbers in a given array of integers using Lambda.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.