Membership Operators in Python
Tags: python, beginners, computerscience, tutorial
Published: 2024-03-27 19:20:40


# Python Unleash'd 01


In any language first thing and ritual of learning programming is to write the Hello World Program. Lets break the coconut by doing the same.

1. PRINT

```
print('Hello World')
print("Hello World")
```

So above both strings are valid. We can not do this

`print("Hi')`

It gives error, **SyntaxError: unterminated string literal**

2. Python Operators are same as every other programming languages. We have arithmetic, relational ( >, <=, != etc), logical (and, or, not)

**Also, there is nothing like === or strict comparison here**

In arithmetic operators we have, 

1. / Division (float): divides the first operand by the second	
2. // Division (floor): divides the first operand by the second
3. % Modulus: returns the remainder when the first operand is divided by the second
4. ** Power (Exponent): Returns first raised to power second

> Exponent is calculated first then (%, *, /, //) then add/subtract.

We can use operators like += /= etc with bitwise also, <<==

Will write separate blog on BITWISE operator as I never tried my hands on it.

Here we have a new category in operators, that is,
**Membership & Identity Operators | Python “in”, and “is” operator**

There are 2 types of membership operators, **in and is**

1. IN

Check if a character/ substring/ element exists in a sequence or not. Evaluates to True 

-  average time complexity of the ‘in’ operator for lists is O(n), for set it is O(1), but for dictionaries we have unique keys, though values can be duplicate so for keys its O(1) while for values it is O(n)

- We have **not in** operator also, 

2. IS

Identity operator evaluates to true if both values are of same type and point to same memory location.

‘is’ operator – Evaluates to True if the variables on either side of the operator point to the same object and false otherwise.

**IN PYTHON VARIABLES WITH SAME MEMORY POINT TO SAME LOCATION WHILE LISTS DO NOT**

**Integers are immutable, so Python keeps a cache of small integers that it uses. Because the objects are cached they always have the same ID.**


Lists are mutable, it would be very unfortunate if changing list_2 messed up list_1 by accident. So they can't be shared unless you do it yourself with list_2 = list_1.

[A MUST READ ON WHAT EXACTLY IS OBJECT](https://medium.com/@thehippieandtheboss/what-is-an-object-in-python-f38f4026a07f#:~:text=A%20Python%20object%20exists%20physically%20in%20your%20computer%20memory&text=The%20variable%20my_name%20is%20just,can%20retrieve%20using%20its%20name.)

One thing I have just noticed, see the below code snippet

```
a = 89
b = 89
print(a is b)
if(id(a) == id(b)):
    print("match")
else:
    print("not a match")
```
**Output **: 

> True
> match

Lets see other code, taking decimal values for a and b

```
a = 8.9
b = 8.9
print(a is b)
if(id(a) == id(b)):
    print("match")
else:
    print("not a match")
```

**Output **: 

> False
> not a match

For decimal we are getting 'not a match' when we have same values

```
a = 890
b = 890
print(a is b)
if(id(a) == id(b)):
    print("match")
else:
    print("not a match")
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uyak7nf0g1j12wcgunie.png)


Here for integer values we are getting output not a match. Try running this on your system also.

Lets dive little deeper into this.

Everything is related to id of object in Python and memory address AND some rules. Now we are aware that everything is object in python and there is memory address of every object.

## Read this

The id() function returns a unique id for the specified object.

All objects in Python has its own unique id.

The id is assigned to the object when it is created.

The id is the object's memory address, and will be different for each time you run the program. (except for some object that has a constant unique id, like integers from -5 to 256)

I have tried above code by replacing values of a and b from -5 to 256 and it is true all that is written above.

### Do read this answer on stackoverflow

[IDs in python](https://stackoverflow.com/a/72705348)

### See how python has the same memory address thing for short string but not for strings with more length


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xqbej4oya8on2bkvl7xg.png)

### As we have seen 'is' behaves differently under different circumstances, then why not to use ==, and when to use == 

[IS vs == ](https://ealexbarros.medium.com/what-is-the-difference-between-and-is-operator-in-python-5ff9000043bf)

1. Use 'is' for object comparison
2. 'is' performs memory address comparison
3. while == performs value based comparison
4. == performs content based comparison



Thanks for reading this blog
Will add more content here as I learn more
Feel free to suggest corrections, share knowledge and feedback in comments