python-3.xany

check if a string list contains a substring


I'm having the following codes to test whether string 'h' is in any of the string in list aa. But it's giving me the TypeError: 'bool' object is not iterable. Why is that?

aa = ['hh', 'ii']
any('h' in aa)
Traceback (most recent call last):
  File "<string>", line 2, in <module>
TypeError: 'bool' object is not iterable

Solution

    1. any('h' in aa) is giving you error exactly as showed in the error message because the conditional returns a boolean which is not an iterable needed for the any function input.
    'h' in aa == False
    'h' in ['hh', 'ii'] == False
    
    1. You can do this conditional as expressed in the comments using list compreension:
    any('h' in w for w in aa)
    
    1. Furthermore, to use this approach in a list of lists as in:
    second_list = [['hh', 'ii'], ['gg', 'kk']]
    any('h' in value for inner_list in second_list for value in inner_list)