In some cases, adding a condition to a comprehension is somewhat like defining another function and then using filter:
T = "cavernous" |
print [c for c in T if c > 'k'] |
def bigrk(letter): |
return letter>'k' |
print filter(bigrk,T) |
print [c+c for c in T if c > 'k'] |
Notice how the filter function makes a
string rather than a list (something that
a comprehension alone cannot do).
In the last line, the comprehension expression
does two things: it filters (larger than
'k' letters only are selected) and doubles
(c+c
). Because the last line
does two things, Python's filter function won't
do the job.