Search code examples
pythonarraysiteration

Removing array entries in loops


I have a program structure with nested loops, and within the innermost loop, I want to delete certain entries from an array (EdgePixels). However, when I try to delete an entry using del, I encounter the error "List index out of range." The code I'm referring to:

for i in range(len(EdgePixels)):
    for j in range(len(EdgePixels)):
        for k in range(len(EdgePixels)):
            # Now in here I want to delete some Entries from the Array...
            # e.g. I want to remove EdgePixels[5], so:
            del EdgePixels[5]

Executing this gives me the error

"List index out of range"...

My goal is to delete entries from the array in the inner loop while allowing the outer loops to continue running with the updated array (without the deleted entries).

Is there a clean way, to solve this?


Solution

  • The easy way would be to ignore indices instead of deleting these elements:

    ignore_indices = set()
    
    for i, item1 in enumerate(EdgePixels):
        if i in ignore_indices:
            continue
        for j, item2 in enumerate(EdgePixels):
            if j in ignore_indices:
                continue
            for k, item3 in enumerate(EdgePixels):
                ignore_indices.add(5)