When it is required to get indices of sign change in a list, a simple iteration along with ‘append’ method can be used.
Example
Below is a demonstration of the same
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): 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, 2, 3, 6]
Explanation
A list is defined and is displayed on the console.
An empty list is defined.
The original list is iterated over, and conditions are set to check if the values at specific indices are less than or greater than 0.
Depending on this, the index is appended to the empty list.
This is displayed as the output on the console.