[Python-ideas] filter-only list comps
denis.spir at gmail.com
Thu Feb 25 14:20:28 CET 2010
I recently realized the following, and wonder whether there is a reason for this, which I am unable to figure out.
A list comp can both map and filter:
[x*x for x in numbers if x%2==1]
When it only maps, we can simply get rid of the filter part:
[x*x for x in numbers]
Meaning we are not forced to write:
[x*x for x in numbers if True]
But the analog does not apply to filter-only list comps:
[x in numbers if x%2==1] # SyntaxError
Why? I find this syntax clear, actually clearer than
[x for x in numbers if x%2==1]
that confusingly repeats the item.
Would there be any parsing issue if we let down "<expression> for" when it does nothing?
Side note: I find the core part of a comprehension be "<item> in <collection>":
[item in collection]
would be equivalent to list(collection).
(item in collection)
would just build an iterator on collection.
From this POV, this core can be preceded by a mapping expression and/or followed by a filtering condition.
la vita e estrany
More information about the Python-ideas