Why is the code below returning FALSE in Python? Shouldn't it be TRUE, because b already includes "T".
a = ["T"]
b = ["H", "T"]
a in b
False
Why is the code below returning FALSE in Python? Shouldn't it be TRUE, because b already includes "T".
a = ["T"]
b = ["H", "T"]
a in b
False
The in
operator behaves differently with strings and with lists. With strings, it's a substring operator: "bc" in "abcd"
is true. With lists, it's a membership operator: 2 in [1,2,3,4]
is true, but [2,3] in [1,2,3,4]
is false since [2,3]
is not an element of the list [1,2,3,4]
.
Think of in
as being primarily a membership test. Strings are a special case because an element of a string is a character, but Python represents characters as strings of length 1. So a member of a string (a character) is a also substring of that string. For strings, in
is a membership test if the left operand is a string of length 1. In other words, when a
is a string of length 1 and b
is a string, a in b
tests whether a
is a member of b
, but under those hypotheses this is equivalent to testing whether a
is a substring of b
. This is extended to a substring test for arbitrary left operands (a
empty or longer than a single character).
If you want to test whether a list is a sublist of another list, see Check for presence of a sliced list in Python
I think you believe that the test should return True
because all items in a
are also in b
, in which case you're really looking to test if a
is a subset of b
, and you should thus make a
and b
sets and use the <=
operator for the test instead:
>>> a = {"T"}
>>> b = {"H", "T"}
>>> a <= b
True
a in b
returns False
because ["T"]
is not an element of ["H", "T"]
. Compare:
>>> a = ["T"]
>>> b = ["H", "T"]
>>> a in b
False
>>> c = "T"
>>> c in b
True
>>> d = ["H", ["T"]]
>>> a in d
True
>>>
You might be thinking of "T" in b
, when expecting True
to be returned. Note that b
is a list of string
s, and a
(ie ["T"]
) is a list
(only with one element:"T"
), so a in b
is necessarily False
.