Saturday, February 9, 2019

Membership Operators

Membership operators are used to check if an item exists in a sequence, such as strings, tuples, lists, dictionaries etc. The table below shows the two membership operators in Python.

+----------+--------------------------------+
|  in      |  if present in a sequence      |
|  not in  |  if not present in a sequence  |
+----------+--------------------------------+

The following examples show how membership operators work.

a = 5
b = 10
c = 'a'
d = 'x'
e = 'hi'
numList = [1, 2, 3, 4, 5]
line = "This is a book"

+--------------------+-----------+
|      Examples      |  Results  |
+--------------------+-----------+
|    a in numList    |   True    |
|    b in numList    |   False   |
|  7 not in numList  |   True    |
|  3 not in numList  |   False   |
|     c in line      |   True    |
|   d not in line    |   True    |
|    'y' in line     |   False   |
|     e in line      |   True    |
|   'his' in line    |   True    |
+--------------------+-----------+

.

No comments: