Vincent Claes Vincent Claes - 6 months ago 11
Python Question

Why is element checking handled differently between list and set?

Why is element checking handled differently between a list and a set?

Let me give the following example:

'a' in ['aa']
returns
False
and
'a' in ('aa')
returns
True

Answer

When you write ('aa') you are simply creating a string, so it is obvious that in will check characters and evaluate as True. You can verify this with

>>> x = ('aa')
>>> print(type(x))
<class 'str'>

As seen in the docs tuple syntax, in order to create a single element tuple you require a trailing comma, i.e. ('aa',). In this case, checking for 'a' inside your tuple will result in False as expected.

If you actually create a set with

x = set('aa')

which is what I imagine you did, a set is created with the unique characters inside your string as elements, since your passed string is seen as an iterable for the set to get elements from (characters). Hence, your set becomes {'a'}, so in will evaluate as True. On the contrary, if you create a set with set literal syntax

x = {'aa'}

a set is created with your single string 'aa', and in will evaluate as False. So it depends on how you initialize a set from 'aa'.

>>> set('dog')
{'d', 'g', 'o'}
>>> {'dog'}
{'dog'}
Comments