Reputation: 26018
Does Python have something like below?
for item in items #where item>3:
#.....
I mean Python 2.7 and Python 3.3 both together.
Upvotes: 39
Views: 63910
Reputation: 214959
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)
Upvotes: 70
Reputation: 968
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
Upvotes: 3
Reputation: 154775
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.
Upvotes: 6
Reputation: 414335
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.
Upvotes: 2
Reputation: 213271
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
Upvotes: 12