Search code examples
pythonloopscomparisoniterationelement

Compare the elements of a list in python


I want to iterate through a list and want to compare the elements of list. For example: First element will be compared with next element. I've a list a:

for i in range(len(a))
    for i+1 in range(len(a)) #check code
        if a[i] == a[i+1]
           a.pop(i+1)

Can anybody suggest how to do this in python?


Solution

  • You are not iterating over the list by element (i.e. for el in a), that is a good thing because I believe modifying a list over which you are iterating wouldn't work. However your approach still has a flaw, in the sense that a number of elements len(a) is calculated at the beginning of the loop and the index doesn't keep into account the fact that you are removing elements, so the inspected element will refer to the position in the list after the pop (skipping elements and exceeding list length). Your example rewritten in a quite straightforward way using a temporary list b:

    a=[1,3,3,6,3,5,5,7]
    
    b=a[0:1]
    for i in range(len(a)-1):
        print (a[i],a[i+1])
        if a[i]!=a[i+1]:
            b.append(a[i+1])
    a=b
    

    Or a one line version:

    from itertools import compress
    list(compress(a,[x!=y for x,y in zip(a[:-1],a[1:])]))
    

    Anyway if your purpose was to remove consecutive duplicate items in a list, you could easily search on google or on stack overflow 'python remove consecutive duplicates from a list'.