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.
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.
It is possible to use multiple variables and conditions in a for loop like in the example given below.
While Loops with multiple conditionsYou can chain together multiple conditions together with logical operators in C++ such as && (And operator) and || (Or operator).
>>> 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)
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++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With