shyamrag cp
shyamrag cp

Reputation: 102

get the index where the continuity breaks first time in python list

Suppose the python list is; my_list = [0,0,0,0,0,1,1,0,0]

The sequence of 0s changes at the index position 5 of the list. Is there a way to return the index when a sequence is changed for the first time in a list?

Upvotes: 2

Views: 839

Answers (3)

N N K Teja
N N K Teja

Reputation: 435

my_list1 = [0,0,0,0,0,1,1,0,0]

def pattern_change(my_list):
    for x in range(1,len(my_list)):
        if my_list[0] != my_list[x]:
            break
    return x

print pattern_change(my_list1)
> 5

Upvotes: 0

DYZ
DYZ

Reputation: 57033

The following reports the index of the 0->1 discontinuity even if the sequence starts with a 1:

my_list1 = [1,0,0,0,0,0,1,1,0,0]
my_list0 = [0,0,0,0,0,1,1,0,0]

zero = my_list1.index(0)
one = my_list1[zero:].index(1) + zero
#6

zero = my_list0.index(0)
one = my_list0[zero:].index(1) + zero
#5

Upvotes: 0

BernardL
BernardL

Reputation: 5434

Just use the index method.

my_list = [0,0,0,0,0,1,1,0,0]

my_list.index(1)
>> 5

Assuming you only have binary elements in your list, .index returns the lowest index of the element you are looking for in the list and would be the equivalent to when the sequence changes.

Or if they are just a sequence of numbers, you can define a helper function to return the first break in sequence by comparing it to the first value.

def changed(li):
    start = li[0]
    change = [i for i in li if i != start][0]
    return li.index(change)

another_list = [1,1,1,0,1,1,1,1]
idx = changed(another_list)

print('index of sequence change: {}\nvalue of sequence change: {}'.format(idx,another_list[idx]))

>>
index of sequence change: 3
value of sequence change: 0

Upvotes: 3

Related Questions