Vincent Claes
Vincent Claes

Reputation: 4768

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

'a' in ('aa') returns True

Upvotes: 2

Views: 58

Answers (2)

miradulo
miradulo

Reputation: 29690

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'}

Upvotes: 3

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22041

Because ('aa') isn't a tuple it's string. Tuple creation operator is ,. So in your use case command 'a' in ('aa') actually checks weather 'a' char present in 'aa' string what is true.

Equivalent operation with tuple would be 'a' in ('aa',) which is falsy.

See more info on python doc#tuple and implicit line joining.

Upvotes: 0

Related Questions