Python's "in" operator with set {}

671 Views Asked by At

I am trying to understand in operator's usage in Python. Is there any difference between the following cases?

Case 1:

a = "Hello"
b = "Help"
b[0] in {a[0]} #case1
>> True

Case 2:
a = "Hello"
b = "Help"
b[0] in a[0] #case2
>> True

Though the outputs are same, I wanted to understand the difference between these two.

3

There are 3 best solutions below

3
On

The first one is a set object with the first letter of a in it, plus the period. It is a sequence type that in can operate on.

The second is a string with a single character in it. It is also a sequence type and the in operator can operate on it as well. The second one has no period in it.

2
On

The in keyword has two purposes:

  1. The in keyword is used to check if a value is present in a sequence (list, range, string etc.).
  2. The in keyword is also used to iterate through a sequence in a for loop:

From the perspective of the in keyword in your examples there is no difference between those two scenarios. They both apply to the first use of the in keyword. The in keyword checks if a variable exists in a set or list of data. You've provided two different valid types of data and checked to see if "H" was in either of them, and you ensured that "H" was in each variable you checked against.

The period should have no effect on the data. All it is is an item in the data which does not match the criteria that in is looking for.

2
On

Literally, the first is equivalent to checking "H" in "H."; in your case, you are iterating both characters of a set. This stops on the first iteration, where the characters match. The . could therefore be anything, True/False, a number, None, etc.

And the second is just checking "H" in "H", which is obviously true