Bootstrap FreeKB - Python (Scripting) - Determine if list contains
Python (Scripting) - Determine if list contains

Updated:   |  Python (Scripting) articles

The in operator is the most common way to determine if a list contains an element, such as a string or integer.

#!/usr/bin/python3
list   = ['foo', 'bar', 'hello world']
string = "foo"

if string in list:
  print(f"{list} contains {string}")
else:
  print(f"{list} does NOT contain {string}")

 

Which should return something like this.

['foo', 'bar', 'hello world'] contains 'foo'

 

However, it is important to recognize that the element in the list must be an exact match. In this example, one of the elements in the list is "hello world".

#!/usr/bin/python3
list   = ['foo', 'bar', 'hello world']
string = "hello"

if string in list:
  print(f"{list} contains {string}")
else:
  print(f"{list} does NOT contain {string}"

 

If searching with just "hello", the following would be returned, because in requires an exact match.

['foo', 'bar', 'hello world'] does NOT contain 'hello'

 

Sometimes, you may want to use any if you want to try to match a substring in a list. In this example, one of the elements in the list is "hello world".

#!/usr/bin/python3
list   = ['foo', 'bar', 'hello world']
string = "el"

if any(string in x for x in list):
  print(f"{list} contains {string}")
else:
  print(f"{list} does NOT contain {string}"

 

When using any, searching with just "el" which is one of the values in "hello world" should match and the following should be returned.

['foo', 'bar', 'hello world'] contains 'el'

 

Or, sometimes it makes more sense to loop through the list and then use re.match to determine if an element in the list matches a regular expression, perhaps something like this.

#!/usr/bin/python3
list   = ['foo', 'bar', 'hello world']
string = "o"

for item in list:
  if re.match(".*"+string+".*", item):
    print(f"{item} contains {string}")
  else:
    print(f"{item} does NOT contain {string}"

 

Which should return the following.

'foo' contains o
'bar' does NOT contain o
'hello world' contains o

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ffc1b5 in the box below so that we can be sure you are a human.