Luke Poeppel Luke Poeppel - 10 days ago 5
Python Question

Python - Printing duplicates after getting previous and next element in a list

Sorry for the beginner question -- In running this code, it prints the output twice rather than printing once and then continuing on to the next iteration of the loop. I'm sure this is simply a formatting error, but I can't seem to spot it... Thanks!

myList = [1, 1, 1, 0.5, 1, 1, 2, 1, 0.5, 1, 3]

for thisThing in myList:
baseIndex = myList.index(thisThing)

if thisThing == 0.5:
get_previous = myList[baseIndex - 1]
get_next = myList[baseIndex + 1]

T2 = thisThing * 2
if T2 == get_previous and T2 == get_next:
print("Success at index " + str(myList.index(thisThing)))
continue

OUTPUT:
Success at index 3
Success at index 3

Answer

index returns the index of first occurrence of the given item, in this case 3. You could fix the code by changing it to iterate index instead:

myList = [1, 1, 1, 0.5, 1, 1, 2, 1, 0.5, 1, 3]

for baseIndex in range(1, len(myList) - 1):
    thisThing = myList[baseIndex]

    if thisThing == 0.5:
        get_previous = myList[baseIndex - 1]
        get_next = myList[baseIndex + 1]

        T2 = thisThing * 2
        if T2 == get_previous and T2 == get_next:
            print("Success at index " + str(baseIndex))

Output:

Success at index 3
Success at index 8

Since the above will only iterate the indexes 1 - 8 it will also work in case that 0.5 is the first or last element.

You could also use enumerate and zip to iterate over tuples (prev, current, next):

for i, (prev, cur, nxt) in enumerate(zip(myList, myList[1:], myList[2:]), 1):
    t2 = cur * 2
    if cur == 0.5 and prev == t2 and nxt == t2:
        print("Success at index " + str(i))