Conditional for in Python

Question:

Does Python have something like below?

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

I mean Python 2.7 and Python 3.3 both together.

Asked By: Alan Coromano

||

Answers:

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
Answered By: Rohit Jain

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)
Answered By: georg

There isn’t a special syntax like the where in your question, but you could always just use an if statement within your for loop, like you would in any other language:

for item in items:
    if item > 3:
        # Your logic here

or a guard clause (again, like any other language):

for item in items:
    if not (item > 3): continue

    # Your logic here

Both of these boring approaches are almost as succinct and readable as a special syntax for this would be.

Answered By: Mark Amery

You could use an explicit if statement:

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

Or you could create a generator if you need a name to iterate later, example:

filtered_items = (n for n in items if n > 3)

Or you could pass it to a function:

total = sum(n for n in items if n > 3)

It might be matter of taste but I find a for-loop combined with inlined genexpr such as for x in (y for y in items if y > 3): to be ugly compared to the above options.

Answered By: jfs

Python 3 and Python 2.7 both have filter() function which allows extracting items out of a list for which a function (in the example below, that’s lambda function) returns True:

>>> nums=[1,2,3,4,5,6,7,8]
>>> for item in filter(lambda x: x>5,nums):
...     print(item)
... 
6
7
8

Omitting function in filter() will extract only items that are True, as stated in pydoc filter

Answered By: Sergiy Kolodyazhnyy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.