0

I want to search if a list contains a string or not. The following code does not compile.

list= []         
list.append("item1")         
list.append("item2")         
list.append("item3")     

if 'item1' in list
    print "yes"  
else  
    print "no"  

Error:

 File "<string>", line 1, in <module>  
  File "/usr/lib/python2.7/py_compile.py", line 117, in compile  
    raise py_exc  
py_compile.PyCompileError:   File "prog.py", line 6  
    if 'item1' in command  
                          ^  
SyntaxError: invalid syntax  
2
  • You need colons after if and else statements. Commented Jun 5, 2015 at 1:02
  • since list is a builtin, you should not use it as a variable name. prefer lst or seq instead, for simple options (though you should usually be able to come up with something more descriptive) Commented Jun 5, 2015 at 1:52

2 Answers 2

1

You need a colon after your if statement/else statement.

Also, I believe in python when you use print it has to go like print(MESSAGE). Edit: Using brackets is the new way in python3.

Try this:

list= []         
list.append("item1")         
list.append("item2")         
list.append("item3")     

if 'item1' in list:
    print("yes")
else: 
    print("no") 
Sign up to request clarification or add additional context in comments.

Comments

1

Syntax for if statement in Python is

 if *condition*:
        statements
 else:
        statements

In your code you miss a colon(:) in if and else part.

list= []         
list.append("item1")         
list.append("item2")         
list.append("item3")

print True if "item1" in list else False

1 Comment

or just print 'item1' in list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.