What's the problem with this range function?

Viewed 39

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]:
        new_list.append(char[i])
        i=i+1
        print (new_list)
1 Answers

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():

lst = ['a','b','b','c','c','a']
from itertools import groupby
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]:
        result.append(item)
print(result)

These output:

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