-3

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_variant
>> True


Case 2:

a = "Hello"
b = "Help"
b[0] in a[0] #case2_variant
>> True

Though the outputs are same, I wanted to understand what the case1_variant stands for.

3 Answers3

1

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.

Keith
  • 42,110
  • 11
  • 57
  • 76
  • can you give another example of using the period in a set with the `in` operator? – shreyas-badiger Nov 18 '18 at 09:21
  • 1
    @hard-fault The period has no special meaning, it's just another element in the set (which isn't used). It could be any other character and it would still work (in fact, if there were no second element it would work, because all you're checking is if the character is _in_ the set, and any other character doesn't affect the result). – Salem Nov 18 '18 at 09:32
  • Thanks! got it. If `a = "Hello"` then `"e" in {a[0], "e"}` gives out `True` – shreyas-badiger Nov 18 '18 at 09:38
0

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.

David Scott
  • 796
  • 2
  • 5
  • 22
0

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    When we talk about "equivalence", I think it's important to note the *means* is different. `set` requires O(*n*) hashing and then an O(1) lookup, while searching for a character in a string is O(*n*). The former will be more efficient if you store the set somewhere and reuse. – jpp Nov 18 '18 at 14:59
  • Still O(n) in both cases, though until rehashing the set objects at least n times – OneCricketeer Nov 18 '18 at 15:11