Find indexes of consecutive items in lists

Viewed 896

I want to take a list like:

x = [1,2,2,3,4,6,6]

and return a 2d list with the indexes of the repeating values:

[ [1,2], [5,6]]

I've tried the following:

new_list = []
i = 0
while i < len(x)-1:
    if x[i] == x[i+1]:
        new_list.append([x[i],x[i+1]]
    i += 1

x is not necessarily sorted but has at least one series of repeating values. For example x can also be:

x = [1,4,2,3,3,3,7,0]
4 Answers

You can use itertools.groupby here.

from itertools import groupby
x=[1, 2, 2, 2, 3, 3, 4, 4, 6, 6, 6, 6, 6, 6, 8]
ranges=[list(g) for _,g in groupby(range(len(x)),lambda idx:x[idx])]
# [[0], [1, 2, 3], [4, 5], [6, 7], [8, 9, 10, 11, 12, 13], [14]]
#   1    2  2  2    3  3    4  4    6  6  6   6   6   6     8

final=[[r[0],r[-1]] for r in ranges if len(r)>1]
# [[1, 3], [4, 5], [6, 7], [8, 13]]

Pure Python approach:

x=[1, 2, 2, 2, 3, 3, 4, 4, 6, 6, 6, 6, 6, 6, 8]
out=[]
count=0
for i in range(1,len(x)):
    prev=x[i-1]
    if x[i]==prev:
        count+=1
    elif count and x[i]!=prev:
        out.append([i-count-1,i-1])
        count=0
if count:
    out.append([i-count,i])

out
# [[1, 3], [4, 5], [6, 7], [8, 13]]

Try this.

def repeating_values( initital_list):
    cache = {}
    result = []
    for i, element in enumerate(initital_list):
        if element in cache:
            result.append([cache[initital_list[i]], i])
        else:
            cache[element] = i

    return result 

For your input


x = [1,2,2,3,4,6,6]

print(repeating_values(x))

Result

[[1, 2], [5, 6]]

You can keep track of the current index and when the next element is equal to the value of the value in current_index, you append it to the result, but you need to increase the value of index until it's value will be different

x = [1, 2, 2, 3, 4, 6, 6]

result = []
cur_idx = 0
i = 1

while i < len(x):
    if x[cur_idx] == x[i]:
        result.append([cur_idx, x[cur_idx]])

        # Increase value of i up to the index where there is different value
        while i < len(x):
            if x[cur_idx] != x[i]:
                # Set cur_idx to the index of different value
                cur_idx = i
                i += 1
                break
            i += 1
    else:
        cur_idx = i
        i += 1

print(result)
# [[1, 3], [5, 3]]

Try this code:

# Hello World program in Python
x = [1,2,2,3,4,6,6]
new_list = []
i = 0
indexes = []
while i < len(x)-1:
    if x[i] == x[i+1]:
        indexes.append(i)
        indexes.append(i+1)
    else:
        indexes = list(set(indexes))
        if len(indexes) != 0:
            new_list.append(indexes)
        indexes = []
    i+=1

indexes = list(set(indexes))
if len(indexes) != 0:
    new_list.append(indexes)
print(new_list)

Result:

[[1, 2], [5, 6]]
Related