Python | Rearrange Positive and Negative Elements

Python | Rearrange Positive and Negative Elements

Rearranging positive and negative elements in a list is a common problem. This tutorial will guide you on how to rearrange the elements of a list such that all negative numbers come before the positive ones. However, the order of the numbers doesn't need to be maintained.

1. Basics:

Let's consider the following list:

arr = [1, -2, 3, -4, 5, -6, -7, 8] 

Our goal is to rearrange it to something like:

[-2, -4, -6, -7, 1, 3, 5, 8] 

2. Using List Comprehension:

The simplest way to rearrange the list is by using list comprehension:

# Separate the negatives and positives negatives = [i for i in arr if i < 0] positives = [i for i in arr if i >= 0] # Concatenate the two lists result = negatives + positives print(result) # [-2, -4, -6, -7, 1, 3, 5, 8] 

3. In-place Rearrangement:

If you need to rearrange the elements without using extra space, you can use a two-pointer approach:

def rearrange(arr): # This function pushes all negative numbers to the left and positives to the right left, right = 0, len(arr) - 1 while left <= right: # If the left element is positive and the right one is negative, swap them if arr[left] > 0 and arr[right] < 0: arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 # If the left element is negative, move the left pointer one step to the right elif arr[left] < 0: left += 1 # If the right element is positive, move the right pointer one step to the left else: right -= 1 arr = [1, -2, 3, -4, 5, -6, -7, 8] rearrange(arr) print(arr) # [-7, -2, -6, -4, 5, 3, 1, 8] 

4. Using Built-in Functions:

Python's sorted function can also be used to achieve this with a custom key:

result = sorted(arr, key=lambda x: x >= 0) print(result) # [-2, -4, -6, -7, 1, 3, 5, 8] 

The lambda function returns True for positive numbers and False for negatives. Since True is equivalent to 1 and False is equivalent to 0, the sorted function will place all negative numbers first.


More Tags

excel-2007 collections orm drag-and-drop db2-400 password-hash jsf row jaxb2 compare

More Programming Guides

Other Guides

More Programming Examples