15

I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code)

    ok = 0
    for x in range(0,10):
        if ok == 1:
            ok = 0
            continue
        for y in range(0,20): 
            if y == 5:
                ok = 1
                continue

What about in this situation?

for attribute in object1.__dict__:
    object2 = self.getobject()
    if object2 is not None:
        for attribute2 in object2: 
            if attribute1 == attribute2:
                # Do something
                #Need the next item of the outer loop

The second example shows better my current situation. I dont want to post the original code because it's in spanish. object1 and object2 are 2 very different objects, one is of object-relational mapping nature and the other is a webcontrol. But 2 of their attributes have the same values in certain situations, and I need to jump to the next item of the outer loop.

0

5 Answers 5

16

Replace the continue in the inner loop with a break. What you want to do is to actually break out of the inner loop, so a continue there does the opposite of what you want.

ok = 0
for x in range(0,10):
    print "x=",x
    if ok == 1:
        ok = 0
        continue
    for y in range(0,20): 
        print "y=",y
        if y == 5:
            ok = 1
            break
Sign up to request clarification or add additional context in comments.

4 Comments

true, my mistake. but I still need to see if I can get the next item of the outer loop in a simpler way :)
@Pablo: getting back to the outer loop immediately is the same as breaking out of the inner loop, isn't it? Or did you mean something else?
@Pablo: I guess you want to avoid using break. I don't think there is any other way to go back to the outer loop from a for loop. The only way that comes to mind is to use a while loop where the looping condition checks for there truth of a flag. This is essentially what ron suggested, and you can easily run a while loop over an iterable like a for loop using an explicit iterator.
It is in the case you dont have code after the inner loop. In the other case, it isnt. But that could work for me now if I modify something plus in your example you dont need the ok flag anymore. Thanks, Im going to accept yours as the answer, it is pretty much close to what I want
3

Your example code is equivalent to (that doesn't seem what you want):

for x in range(0, 10, 2):
    for y in range(20): 
        if y == 5:
           continue

To skip to the next item without using continue in the outer loop:

it = iter(range(10))
for x in it:
    for y in range(20):
        if y == 5:
           nextx = next(it)
           continue

Comments

1

You can always transform into a while loop:

flag = False
for x in range(0, 10):
    if x == 4: 
        flag = True
        continue

becomes

x = 0
while (x != 4) and x < 10:
    x += 1
flag = x < 10

Not necessary simpler, but nicer imho.

1 Comment

Thanks, but I posted a bad example. In my current situation I'm working with objects instead of numbers.
0

So you're not after something like this? I'm assuming that you're looping through the keys to a dictionary, rather than the values, going by your example.

for i in range(len(object1.__dict__)):
  attribute1 = objects1.__dict__.keys()[i]
  object2 = self.getobject() # Huh?
  if object2 is not None:
    for j in range(len(object2.__dict__)):
      if attribute1 == object2.__dict__.keys()[j]:
        try:
          nextattribute1 = object1.__dict__.keys()[i+1]
        except IndexError:
          print "Ran out of attributes in object1"
          raise

Comments

0

It's not completely clear to me what you want, but if you're testing something for each item produced in the inner loop, any might be what you want (docs)

>>> def f(n):  return n % 2
... 
>>> for x in range(10):
...     print 'x=', x
...     if f(x):
...         if any([y == 8 for y in range(x+2,10)]):
...             print 'yes'
... 
x= 0
x= 1
yes
x= 2
x= 3
yes
x= 4
x= 5
yes
x= 6
x= 7
x= 8
x= 9

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.