Why is 'a' in ('abc') True while 'a' in ['abc'] is False?

When using the interpreter, the expression 'a' in ('abc') returns True, while 'a' in ['abc'] returns False. Can somebody explain this behaviour?


Solution 1:

('abc') is the same as 'abc'. 'abc' contains the substring 'a', hence 'a' in 'abc' == True.

If you want the tuple instead, you need to write ('abc', ).

['abc'] is a list (containing a single element, the string 'abc'). 'a' is not a member of this list, so 'a' in ['abc'] == False

Solution 2:

('abc') is not a tuple. I think you confused that with tuple ('abc',).

Actually, ('abc') is same as 'abc', an array of characters where a as character is in it, hence, the first lookup returns True:

>>> 'a' in 'abc'
True

On the other hand, ['abc'] is a list of string or a list of list of characters (you can think of it as a 2-d matrix of characters [['a', 'b', 'c']]) where a, as a single character, is not the member of the outer list. In fact, it is the first character of the inner list:

>>> 'a' in ['abc']
False

>>> 'a' in ['abc'][0]
True

>>> 'a' == ['abc'][0][0]
True

Solution 3:

For ('abc') you get 'a' in ('abc') return true.

But for ['abc'] as it is a array list you get 'a' in ['abc'] return false.

Example:

Input: ('abc') == 'abc'

Output: True

So if we call 'a' in ('abc') it is same as 'a' in 'abc' because ('abc') is not a tuple but 'abc' is a array of character where character 'a' is in index 0 of string 'abc'.

On the other hand ['abc'] is array list where 'abc' is a single string which is at index 0 of array ['abc'].

Tupple Example: x = ('abc', 'def', 'mnop')

Array Example: x = ['abc', 'def', 'mnop']

or

x = ('abc'), y = 'abc'

Here always x == y.

But in case of 'a' in ['abc'] =>

x = ['abc'], y = 'abc'

Here x != y but x[0] == y

Solution 4:

As others has mentioned, ('abc') is not a tuple. 'a' is not a element of ['abc']. The only element in that list is 'abc'

x='abc' in ['abc']

print (x)

True #This will evaluate to true

This will also evaluate to true:

y = 'a' in ['a','b','c']

print (y)

True