Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to combine FOR loop and IF statement

I know how to use both for loops and if statements on separate lines, such as:

>>> a = [2,3,4,5,6,7,8,9,0] ... xyz = [0,12,4,6,242,7,9] ... for x in xyz: ...     if x in a: ...         print(x) 0,4,6,7,9 

And I know I can use a list comprehension to combine these when the statements are simple, such as:

print([x for x in xyz if x in a]) 

But what I can't find is a good example anywhere (to copy and learn from) demonstrating a complex set of commands (not just "print x") that occur following a combination of a for loop and some if statements. Something that I would expect looks like:

for x in xyz if x not in a:     print(x...) 

Is this just not the way python is supposed to work?

like image 775
ChewyChunks Avatar asked Aug 08 '11 11:08

ChewyChunks


People also ask

How do you use if loop and if statements together?

Create a for- loop to repeatedly execute statements a fixed number of times. Create a while- loop to execute commands as long as a certain condition is met. Use if-else constructions to change the order of execution.

Can you put a For loop in an if statement?

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.

Can you nest a For loop in an if statement Python?

If statement within a for loopInside a for loop, you can use if statements as well.

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

for in Loop: 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++).


1 Answers

You can use generator expressions like this:

gen = (x for x in xyz if x not in a)  for x in gen:     print(x) 
like image 113
Kugel Avatar answered Sep 30 '22 18:09

Kugel