Python Program to get indices of sign change in a list

When it is required to get indices of sign change in a list, a simple iteration along with append method can be used. A sign change occurs when consecutive numbers have different signs (positive to negative or negative to positive).

Example

Below is a demonstration of finding sign change indices ?

my_list = [71, 24, -34, -25, -76, 87, 29, -60, 70, 8]

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

my_result = []
for index in range(0, len(my_list) - 1):
    # Check for sign change between current and next element
    if (my_list[index] > 0 and my_list[index + 1] < 0) or (my_list[index] < 0 and my_list[index + 1] > 0):
        my_result.append(index)

print("The result is :")
print(my_result)

Output

The list is :
[71, 24, -34, -25, -76, 87, 29, -60, 70, 8]
The result is :
[1, 5, 7]

How It Works

The algorithm checks each consecutive pair of numbers:

  • Index 1: 24 (positive) ? -34 (negative) = Sign change

  • Index 5: -76 (negative) ? 87 (positive) = Sign change

  • Index 7: -60 (negative) ? 70 (positive) = Sign change

Alternative Approach Using Multiplication

You can also detect sign changes by checking if the product of consecutive numbers is negative ?

my_list = [71, 24, -34, -25, -76, 87, 29, -60, 70, 8]

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

my_result = []
for index in range(len(my_list) - 1):
    # If product is negative, signs are different
    if my_list[index] * my_list[index + 1] < 0:
        my_result.append(index)

print("The result is :")
print(my_result)
The list is :
[71, 24, -34, -25, -76, 87, 29, -60, 70, 8]
The result is :
[1, 5, 7]

Conclusion

Use explicit sign comparison for clarity or multiplication method for conciseness. Both approaches effectively identify indices where sign changes occur between consecutive elements in a list.

Updated on: 2026-03-26T02:07:57+05:30

544 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements