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

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

('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 - Python

('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 - Python

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 - Python

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

Solution 5 - Python

('abc') is equivalent to 'abc'.

'a' in ('abc') is equivalent to 'a' in 'abc'.

'a' in ('abc', ) returns False as 'a' in ['abc'].

'a' in ['a', 'b', 'c'] returns True as 'a' in 'abc'.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlverView Question on Stackoverflow
Solution 1 - PythondhkeView Answer on Stackoverflow
Solution 2 - PythonOzgur VatanseverView Answer on Stackoverflow
Solution 3 - PythonM.A.K. RiponView Answer on Stackoverflow
Solution 4 - PythondyaoView Answer on Stackoverflow
Solution 5 - PythonsevenforceView Answer on Stackoverflow