Reputation: 4349
Filter clauses in list comprehension,
As one particularly useful extension, the for loop nested in a comprehension expression can have an associated if clause to filter out of the result items for which the test is not true.
//This will return the list of all the even numbers in range 100
print [index for index in range(100) if 0 == index%2]
But I am looking at possibility of adding a function that can be called for evaluating the condition.? With this feature I will be able to add more complex conditions in it.
Something like this,
def is_even(x):
return 0 is x%2
print [index +100 for index in range(10) 0 is_even(index)]
Upvotes: 0
Views: 67
Reputation: 239653
Yes, you can very well add that. The construct would look similar to the normal filtering condition
def is_even(x):
return 0 == x%2
print [index + 100 for index in range(10) if is_even(index)]
As long as the function returns a truthy value1, the filtering will work as expected.
Note: Use ==
to check if two values are equal, instead of using is
operator. The is
operator is used to check if the objects being compared are one and the same.
1 Quoting from Python's official documentation,
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False
,None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
So, as long as your function returns anything other than the falsy items mentioned on the above list, the condition will be satisfied.
Apart from that, Python's List comprehension's syntax allows you to have multiple if
clauses in it. For example, lets say you want to find all the multiples of 3
which are not multiples of 5
within 30, you can write it like this
>>> [index for index in range(30) if index % 3 == 0 if index % 5 != 0]
[3, 6, 9, 12, 18, 21, 24, 27]
It will have the same effect as
>>> [index for index in range(30) if index % 3 == 0 and index % 5 != 0]
[3, 6, 9, 12, 18, 21, 24, 27]
Upvotes: 5