Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating through a list with an if statement

I have a list that I am looping through with a "for" loop and am running each value in the list through an if statement. My problem is that I am trying to only have the program do something if all the values in the list pass the if statement and if one doesn't pass, I want it to move along to the next value in the list. Currently it is returning a value if a single item in the list passes the if statement. Any ideas to get me pointed in the right direction?

like image 540
Lance Collins Avatar asked May 28 '11 21:05

Lance Collins


People also ask

Can you iterate with if?

The If statement by itself cannot be considered iteration . You can run a code block containing an if statement as many times as you wish, but this doesn't make the if statement an iterator by itself. It's what calls that code block which could stand for iteration.

Can you use an IF statement in a for loop?

You can nest If statements inside For Loops. For example you can loop through a list to check if the elements meet certain conditions. You can also have a For Loop inside another For loop.

How do you iterate through a list without a loop in Python?

Looping without a for loopGet an iterator from the given iterable. Repeatedly get the next item from the iterator. Execute the body of the for loop if we successfully got the next item. Stop our loop if we got a StopIteration exception while getting the next item.


1 Answers

Python gives you loads of options to deal with such a situation. If you have example code we could narrow that down for you.

One option you could look at is the all operator:

>>> all([1,2,3,4])
True
>>> all([1,2,3,False])
False

You could also check for the length of the filtered list:

>>> input = [1,2,3,4]
>>> tested = [i for i in input if i > 2]
>>> len(tested) == len(input)
False

If you are using a for construct you can exit the loop early if you come across negative test:

>>> def test(input):
...     for i in input:
...         if not i > 2:
...             return False
...         do_something_with_i(i)
...     return True

The test function above will return False on the first value that's 2 or lower, for example, while it'll return True only if all values were larger than 2.

like image 156
Martijn Pieters Avatar answered Sep 28 '22 21:09

Martijn Pieters