Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional for in Python

Tags:

python

Does Python have something like below?

for item in items #where item>3:   #..... 

I mean Python 2.7 and Python 3.3 both together.

like image 519
Alan Coromano Avatar asked Oct 20 '12 09:10

Alan Coromano


People also ask

What is a conditional used for in Python?

Decision-making in a programming language is automated using conditional statements, in which Python evaluates the code to see if it meets the specified conditions. The conditions are evaluated and processed as true or false. If this is found to be true, the program is run as needed.

What are the 3 types of Python conditional statements?

In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation. In Python, it is permissible to write the above block in one line, which is similar to the above block.

Is for loop conditional?

The While loop and the For loop are the two most common types of conditional loops in most programming languages.

Does Python have conditional and?

Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.)


2 Answers

You can combine the loop with a generator expression:

for x in (y for y in items if y > 10):     .... 

itertools.ifilter (py2) / filter (py3) is another option:

items = [1,2,3,4,5,6,7,8]  odd = lambda x: x % 2 > 0  for x in filter(odd, items):     print(x) 
like image 84
georg Avatar answered Sep 25 '22 16:09

georg


You mean something like this: -

item_list = [item for item in items if item > 3] 

Or, you can use Generator expression, that will not create a new list, rather returns a generator, which then returns the next element on each iteration using yield method: -

for item in (item for item in items if item > 3):     # Do your task 
like image 38
Rohit Jain Avatar answered Sep 21 '22 16:09

Rohit Jain