[Tutor] Iterating over a list for a certain character...

Gregor Lingl glingl@aon.at
Fri, 14 Dec 2001 00:42:31 +0100


> > 
> 
> take a look at:
> 
> >>> c = 's'
> >>> c in 'streets'
> 1
> 
> 
P.S.:

In Python 2.2 the following also  will work:

>>> l = ['bim','bam','schrumm']
>>> def wordswith(c,l):
    return filter(lambda x: c in x, l)

>>> wordswith('b',l)
['bim', 'bam']
>>> 

.. due to 'nested_scopes' in action

---------------------------------------------------

Alternately you may use (already since Python 2.0 ?)

>>> [word for word in l if 'b' in word]
['bim', 'bam']
>>> 

and consequently

>>> def wordswith(c,lst):
...  return [word for word in lst if c in word]
... 
>>> wordswith('m',l)
['bim', 'bam', 'schrumm']
>>> wordswith('b',l)
['bim', 'bam']
>>>  ww('x',l)
[]
>>> 

Gregor