Grep on elements of a list

Use filter():

>>> names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
>>> filter(lambda x:'aet' in x, names)
['aet2000', 'aet2001']

with regex:

>>> import re
>>> filter(lambda x: re.search(r'aet', x), names)
['aet2000', 'aet2001']

In Python 3 filter returns an iterator, hence to get a list call list() on it.

>>> list(filter(lambda x:'aet' in x, names))
['aet2000', 'aet2001']

else use list-comprehension(it will work in both Python 2 and 3:

>>> [name for name in names if 'aet' in name]
['aet2000', 'aet2001']

Try this out. It may not be the "shortest" of all the code shown, but for someone trying to learn python, I think it teaches more

names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
found = []
for name in names:
    if 'aet' in name:
       found.append(name)
print found

Output

['aet2000', 'aet2001']

Edit: Changed to produce list.

See also:

How to use Python to find out the words begin with vowels in a list?

Tags:

Python

List

Grep