Course Content
Introduction to Python
Introduction to Python
Membership Operators and Type Comparisons in Python
Python also provides membership operators, which check whether a sequence exists within an object. In Python, sequence objects include strings, lists, tuples, and more. These will be explored in the next section.
The membership operators are in
and not in
. The in
operator returns True
if the sequence exists within the object. For example, let's check if the letter 'n'
is in the word 'codefinity'
.
# Initial string site = "codefinity" # Using membership operator print("n" in site)
A True
result means the letter was found in the word. Conversely, the not in
operator checks if a sequence is absent from an object.
Sometimes, it's necessary to verify an object's type. For example, when dividing an input by 2
, the value must be numerical; otherwise, the operation will fail. There are two ways to check a value's type:
- Using
is
:type(var) is int
returnsTrue
only ifvar
is an integer. - Using
isinstance()
:isinstance(var, int)
does the same but works with multiple types.
# Initial number num = 3.5 # Checking if num is an integer print(type(num) is int) # The first approach print(isinstance(num, int)) # The second approach
As shown, both methods return False
because 3.5
is a float
, not an int
.
Thanks for your feedback!