1

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])
Community
  • 1
  • 1
Huxwell
  • 171
  • 2
  • 14
  • *having return in the middle of constructor looses sense* You could still use a function and call it from the contructor. – sloth Oct 19 '15 at 10:22
  • 1
    Note that you should use `len(neurons)` rather than `neurons.__len__()`. What's the problem with `break`? – jonrsharpe Oct 19 '15 at 10:22
  • 2
    Your example is not a case of breaking out of nested loops. At the point you seem to be wishing to break from the loops are not nested (yet). Then what's the problem with using `break`? – skyking Oct 19 '15 at 10:26
  • Sorry; my mistake; break applied on lowest depth works ok. I don't delete question though, since i generally want to know how to get out of nested loop with enumerate earlier. – Huxwell Oct 19 '15 at 11:25

3 Answers3

0

You can also just use break:

for i in range(1,100):
  if i==10:
    break

That will kill the loop as soon as a condition is matched.

Henry
  • 1,646
  • 12
  • 28
  • But surely you can just apply this condition on the `if layerId == neurons.__len__() -1` condition. – Henry Oct 19 '15 at 10:23
0

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)
skyking
  • 13,817
  • 1
  • 35
  • 57
0

I would recommend you to implement your neurons object as a class with method __iter__ to make the object iterable according to the behavior you like:

class MyClass(object):
    def __iter__(self):
        yield 2
        yield 5
        yield 10


obj = MyClass()

for i in obj:
    print i
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95