Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loops and multiple conditions

In C++, it's possible to say:

for (int i = 0; i < 100 && !found; i++) {
  if (items[i] == "the one I'm looking for")
    found = true;
}

so you don't need to use the "break" statement.

In Python, I guess you need to write:

found = False

for item in items:
    if item == "the one I'm looking for"
        found = True
        break

I know that I can write a generator which has the same code in it so I can hide this break thing. But I wonder if there is any other way to implement the same thing (with the same performance) without using extra variables or while loop.

I know we can say:

found = "the one I'm looking for" in items

I'm just trying to learn if it's possible to use multiple conditions in for loops.

Thanks.

like image 839
pocoa Avatar asked May 26 '11 04:05

pocoa


People also ask

Can a for loop have multiple conditions?

It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.

Can you have multiple conditions in a for loop Java?

It is possible to use multiple variables and conditions in a for loop like in the example given below.

Can you put two conditions in a for loop C++?

While Loops with multiple conditionsYou can chain together multiple conditions together with logical operators in C++ such as && (And operator) and || (Or operator).


2 Answers

>>> from itertools import dropwhile
>>> try:
...     item = next(dropwhile(lambda x: x!="the one I'm looking for", items))
...     found = True
... except:
...     found = False

Of course you can also write this without the lambda function as

>>> from itertools import dropwhile
>>> try:
...     item = next(dropwhile("the one I'm looking for".__ne__, items))
...     found = True
... except:
...     found = False

Now it looks to me that it is the C version using extra variables

If you really just need the found variable set (and don't need to know the item), then simply use

found = any(item=="the one I'm looking for" for item in items)
like image 85
John La Rooy Avatar answered Oct 10 '22 07:10

John La Rooy


Since for loops in Python iterate over a sequence rather than a condition and a mutation statement, the break is necessary to bail out early. In other words, for in python isn't a conditional loop. The Python equivalent to C++'s for would be a while loop.

i=0
found=False
while i < 100 and !found:
    if items[i] == "the one I'm looking for":
        found=True
    i += 1

Even in C++, for loops can be rewritten as while loops if they don't contain a continue statement.

{
    int i = 0;
    while (i < 100 && !found) {
        if (items[i] == "the one I'm looking for")
            found = true;
        i++;
    }
}
like image 27
outis Avatar answered Oct 10 '22 07:10

outis