[SOLVED] What’s the problem with this range function?


This Content is from Stack Overflow. Question asked by Maryam

I have a list and I want to get one element from two similar consecutive elements. (sort or if is not in new_list doesn’t work as I want to keep those similar elements that are not consecutive)

I’ve written this, but it returns an error with the range function that [i+1] is not in the range:

like: input: [‘a’,’b’,’b’,’c’,’c’,’a’]
output: [‘a’,’b’,’c’,’a’]

list = ['a','b','b','c','c','a']
new_list = []
for i in range(0,len(list)+1):  
    if  list[i]!=list[i+1]:
        print (new_list)


There’s a couple of issues here (indexing issues, using list as a variable name which shadows a builtin), but the simplest way to do this is to use itertools.groupby():

from itertools import groupby

lst = ['a','b','b','c','c','a']
print([key for key, _ in groupby(lst)])

If you can’t use groupby(), you can check whether you’ve already added the first letter in the current streak of letters (i.e. check if the last item in your accumulated result matches the letter you’re currently examining):

lst = ['a','b','b','c','c','a']
result = []
for item in lst:  
    if not result or item != result[-1]:

These output:

['a', 'b', 'c', 'a']

This Question was asked in StackOverflow by Maryam and Answered by BrokenBenchmark It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?