Search code examples
pythoniterationneural-networknested-loops

How to end loop one iteration earlier?


I often need to end loop one iteration earlier, how do I do it elegantly? Breaking out of nested loops looks messy to me. For now I workaround it with return, but when later on I want to make a class, having return in the middle of constructor looses sense.

def forward(neurons):
for layerId, layer in enumerate(neurons):
    if layerId == neurons.__len__() - 1:
        return
    for idx, i in enumerate(neurons[layerId]):
        for idx2, n in enumerate(neurons[layerId+1]):
            neurons[layerId+1][idx2] += i * sigmoid(weights[layerId][idx][idx2])

Solution

  • One generic solution would be to create a generator from the iterator (that will yield all but the last element the iterator yields):

    def but_last(p):
        first = True
        for x in p:
            if not first:
                yield last
            first = False
            last = x
    
    for layerId, layer in but_last(enumerate(neurons)):
        do_your_stuff(layerId, layer)