-1

I do not understand the logical idea of this behavior:

d = {'a': 'a',
     'b': 'b',
     }

print('' in d['a']) #---> True
print(d['a'] in '') #---> False

can someone help me?

7
  • 1
    This has nothing to do with the dictionary, In Python the empty string is inside any non-empty string Commented Apr 22, 2021 at 20:35
  • What does the dict have to do with it? Commented Apr 22, 2021 at 20:35
  • @wjandrea I think that's what was confusing the OP. A common confusion thinking it would return false because '' is not in d. (I'm just speculating) Commented Apr 22, 2021 at 20:36
  • 1
    That and the in operator is not commutative. Commented Apr 22, 2021 at 20:36
  • 1
    Did you mean to use ==? in is almost never commutative. The only exception is when == is True. Commented Apr 22, 2021 at 20:36

1 Answer 1

2

It's because it's searching the string 'a', if you ask if an empty string is in a non-empty string (or an empty string) it will return true.

What you are really asking is:

'' in 'a'
Out: True  # Notice that 'a' is the same as '' + 'a'

'a' in ''
Out: False
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.