Python – Group Consecutive elements by Sign

When working with lists of numbers, you might need to group consecutive elements by their sign (positive or negative). This can be achieved using the XOR operator (^) along with enumeration to detect sign changes between consecutive elements.

Understanding the XOR Operator for Sign Detection

The XOR operator (^) helps detect when two numbers have different signs. When applied to numbers with different signs, the result is negative, indicating a sign change.

Example

Here's how to group consecutive elements by their sign ?

numbers = [15, -33, 12, 64, 36, -12, -31, -17, -49, 12, 43, 30, -23, -35, 53]

print("The list is:")
print(numbers)

result = [[]]
for index, element in enumerate(numbers):
    if index > 0 and element ^ numbers[index - 1] < 0:
        result.append([element])
    else:
        result[-1].append(element)

print("The result is:")
print(result)
The list is:
[15, -33, 12, 64, 36, -12, -31, -17, -49, 12, 43, 30, -23, -35, 53]
The result is:
[[15], [-33], [12, 64, 36], [-12, -31, -17, -49], [12, 43, 30], [-23, -35], [53]]

How It Works

The algorithm works by:

  • Starting with an empty list of lists to store grouped elements

  • Iterating through the list using enumerate() to get both index and element

  • Using the XOR operator to check if the current element has a different sign than the previous one

  • If signs differ (XOR result

  • If signs are the same, adding the element to the current group

Alternative Approach Using itertools.groupby

You can also use itertools.groupby with a sign function ?

import itertools

numbers = [15, -33, 12, 64, 36, -12, -31, -17, -49, 12, 43, 30, -23, -35, 53]

# Group by sign (positive or negative)
grouped = [list(group) for key, group in itertools.groupby(numbers, key=lambda x: x >= 0)]

print("Using itertools.groupby:")
print(grouped)
Using itertools.groupby:
[[15], [-33], [12, 64, 36], [-12, -31, -17, -49], [12, 43, 30], [-23, -35], [53]]

Conclusion

The XOR operator provides an efficient way to detect sign changes between consecutive numbers. Both the manual approach and itertools.groupby effectively group consecutive elements by their sign, with the latter being more readable for complex scenarios.

Updated on: 2026-03-26T00:55:17+05:30

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements