sam
sam

Reputation: 19164

check if the element is present in list or not

I have a list hi

w = ['4KUI_YLR242C.pdb', '2CQA_CGI-52.pdb', '4G4S_YFR051C.pdb']


if '4KUI' in w:
    print "got !!"

But, I am not able to print 'got'. how can I do that?

Upvotes: 0

Views: 225

Answers (5)

Ben Crowhurst
Ben Crowhurst

Reputation: 8481

Example

#!/usr/bin/python

entries = ['Glasgow', 'Edinburgh', 'Scotland', 'Dundee']

if [entry for entry in entries if entry.startswith('Dun')]:
        print "Found entry for Dundee"

Execution

python example.py

Upvotes: 0

suspectus
suspectus

Reputation: 17258

w = ['4KUI_YLR242C.pdb', '2CQA_CGI-52.pdb', '4G4S_YFR051C.pdb']

for item in w:
        if "4KUI" in item:
                print "got !!"

Upvotes: 0

JoshL
JoshL

Reputation: 10988

In this context "in" is determining whether '4KUI' is the value of one of the elements in your list. What you want is to see if '4KUI' is contained within one of the elements in your list. Try this:

w = ['4KUI_YLR242C.pdb', '2CQA_CGI-52.pdb', '4G4S_YFR051C.pdb']

for f in w:
  if '4KUI' in f:
    print "got !!"

Upvotes: 0

Ajurna
Ajurna

Reputation: 561

you are comparing the whole string there. you need to do something like

for string in w:
    if '4kui' in string:
        print "got!!"

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113905

This is because there is no element in w that is '4KUI'. There certainly is one that starts that way, though.
I think this is what you're looking for:

w = ['4KUI_YLR242C.pdb', '2CQA_CGI-52.pdb', '4G4S_YFR051C.pdb']
if any(i.startswith("4KUI") for i in w):
    print "got !!"

Upvotes: 5

Related Questions