Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

You can use generator expressions for combining for loop and if statement for this:

gen = (x for x in xyz if x not in a) 

for x in gen: 

print x

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...