compare current item to next item in a python list
python
Solution
You can use enumerate:
mylist = [1, 2, 2, 4, 2, 3]
for i, j in enumerate(mylist[:-1]):
if j == mylist[i+1]:
mylist[i] = "foo"
mylist[i+1] = "foo"
print mylist
[1, 'foo', 'foo', 4, 2, 3]
`j` is the current element in the iteration, `mylist[i+1]` is the next, if `j=4`,`mylist[i+1] = 2` etc.. `mylist[:-1]` loops through all the elements except the last so the last `mylist[i+1]` get the last element in the list.
Problem
Considering a python list, how can I compare current item to next it ? for example: ``` mylist = [1, 2, 2, 4, 2, 3] for i in mylist: if i == next item: replace (both i and next item) with "same value" >>> [1, "same value", "same value", 4, 2, 3] ```