Compare the elements of a list in python
Solution 1
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'.
Solution 2
for this, next_one in zip(a, a[1:]):
compare(this, next_one)
Related videos on Youtube
Sachin Chauhan
Updated on June 04, 2022Comments
-
Sachin Chauhan almost 2 years
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?
-
juanpa.arrivillaga over 6 yearsWhat, exactly are you trying to accomplish? What is your expected output?
-
AChampion over 6 yearsAre you just looking to remove consecutive duplicates?
-
Vincenzooo over 6 yearsPossible duplicate of How do I remove consecutive duplicates from a list?
-
-
adhg over 3 yearsdont use 'next': Assignment to reserved built-in symbol: next