Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare current item to next item in a python list [duplicate]

Tags:

python

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]  
like image 752
Juli Avatar asked Nov 28 '22 15:11

Juli


1 Answers

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.

like image 190
Padraic Cunningham Avatar answered Dec 05 '22 14:12

Padraic Cunningham