Python value in array (list) check

In Python we frequently need to check if a value is in an array (list) or not. Python x in list can be used for checking if a value is in a list. Note that the value type must also match. Here is a quick example:

a = ["1", "2", "3"]
if "2" in a:
  print "string 2 is in array a"
else:
   print "string 2 is not in array a"
if 2 in a:
  print "number 2 is in array a"
else:
   print "number 2 is not in array a"
string 2 is in array a
number 2 is not in array a
Env: Python 2.7.6
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments