List search

Tim Williams tdwdotnet at
Fri Sep 28 23:04:07 CEST 2007

On 28/09/2007, Kevin Walzer <kw at> wrote:
> I'm having a problem with searching a list. Here's my code:
> mylist = ['x11', 'x11-wm', 'x11-system']
> for line in mylist:
>        if 'x11' in line:
>                print line
> This results in the following output:
> x11
> x11-wm
> x11-system

That output is correct,  you are asking your script to print any list
item containing x11 when what you actually wanted was a list item that
is the string 'x11'

mylist = ['x11', 'x11-wm', 'x11-system']
for item in mylist:
      if item ==  'x11':
               print line

If there is only ever one 'x11' in the list you could also consider

print mylist.index('x11')


print mylist[mylist.index('x11')]

Also, before iterating the whole list check that 'x11' exists

if 'x11' in mylist:
    do stuff

and list comprehesions

print [x for x in mylist if x == 'x11']

HTH :)

Tim Williams

More information about the Python-list mailing list