Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do "if-for" statement in python?

Tags:

python

With python, I would like to run a test over an entire list, and, if all the statements are true for each item in the list, take a certain action.

Pseudo-code: If "test involving x" is true for every x in "list", then do "this".

It seems like there should be a simple way to do this.

What syntax should I use in python?

like image 221
Zack Maril Avatar asked Dec 03 '10 18:12

Zack Maril


People also ask

How do you write a condition in a for loop in Python?

For Loop in Python For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).

How do you do a 3 for loop in Python?

Example. #!/usr/bin/python3 for letter in 'Python': # traversal of a string sequence print ('Current Letter :', letter) print() fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # traversal of List sequence print ('Current fruit :', fruit) print ("Good bye!")

Can FOR loops have if statements?

You can put a for loop inside an if statement using a technique called a nested control flow. This is the process of putting a control statement inside of another control statement to execute an action. You can put an if statements inside for loops.


2 Answers

Use all(). It takes an iterable as an argument and return True if all entries evaluate to True. Example:

if all((3, True, "abc")):
    print "Yes!"

You will probably need some kind of generator expression, like

if all(x > 3 for x in lst):
    do_stuff()
like image 151
Sven Marnach Avatar answered Oct 13 '22 20:10

Sven Marnach


>>> x = [True, False, True, False]
>>> all(x)
False

all() returns True if all the elements in the list are True

Similarly, any() will return True if any element is true.

like image 44
user225312 Avatar answered Oct 13 '22 20:10

user225312