[Python-ideas] for-loop-if like list comps have?
Christopher Welborn
cjwelborn at live.com
Sat Mar 15 03:07:18 CET 2014
mylist = ['apple', 'banana', 'orange', 'grapefruit']
# Why is this okay...
for item in [x for x in mylist if 'p' in x]:
print(item)
# But this isn't?
for item in mylist if 'p' in item:
SyntaxError: invalid syntax
# Instead you have to do another nesting level..
for item in mylist:
if 'p' in item:
print(item)
# Or another way.
for item in mylist:
if 'p' not in item:
continue
print(item)
...And there is 'filter', 'lambdas', and whatever else
to achieve the same result. But the list comprehension
is already closely related to a for-loop, and it seems
natural to go from:
[x for x in mylist if x]
to:
for x in mylist if x:
Just an idea, sorry if it has been mentioned before.
--
\¯\ /¯/\
\ \/¯¯\/ / / Christopher Welborn (cj)
\__/\__/ / cjwelborn at live·com
\__/\__/ http://welbornprod.com
More information about the Python-ideas
mailing list