Home > Mobile >  Why does "TypeError: 'bool' object is not iterable" occur?
Why does "TypeError: 'bool' object is not iterable" occur?

Time:01-06

>>> l1 = [1,2,3]
>>> l2 = [1,2]
>>> assert all(any(x in l1 for x in l2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not iterable

I want to check whether l2 is included in l1.

CodePudding user response:

Just call all(), not any().

assert(all(x in l1 for x in l2))

You can also use set operations:

assert(set(l2) <= set(l1))

CodePudding user response:

any works this way:

Return True if bool(x) is True for any x in the iterable.

So any(x in l1 for x in l2) returns a bool, which is not a proper argument for all.

CodePudding user response:

Iterate over l2, and check that each value is in l1.

assert all(x in l1 for x in l2)

Since ints are hashable, you can create a set and check if it is a subset of the other list (set.issubset can handle arbitrary iterable values).

assert set(l2).issubset(l1)
  •  Tags:  
  • Related