In Python Operator Usage Tutorial with Examples – POFTUT

In Python Operator Usage Tutorial with Examples


Python provides a lot of operators for comparison, checking existence etc. in operator is very popular operator used to check given values in given variables, list, dictionaries etc. In this tutorial we will look different use cases and examples of in operator.

Check List

Python lists provides elements in single item like an array. in keyword can be used to check given values in this list whether exist or not. We will simply provide the value we are looking for before in keyword and then the list or list variable. In this example we are looking for 3 in the list named mylist

mylist = [1,2,3,4,5,6] 
3 in mylist 
#True
Check List
Check List

This will return True boolean value because 3 exists in mylist

Check Dictionary

Another use case for in operator is dictionaries. Dictionary is similar but a bit different from list data structure. We can use in operator to check presence of the dictionary key. In this example we will check if key name exist in dictionary mydict .

mydict={'name':'poftut','surname':'com'} 
'name' in mydict 
#True
Check Dictionary
Check Dictionary

As we see name exist as a key in dictionary mydict

Check Set

Set data structures holds elements like mathematical sets. They do not hold same value multiple times. We can use in operator to check an element existence in set. We will check if a exists in set named myset .

myset=('a','b','c') 
'a' in myset 
#True
Check Set
Check Set

As we can see a exists in set named myset

Use With Generators

Python provides practical functions in order to generate numbers or other values in an iterable format. range and xrange functions are used to generate numbers. in keyword can be used to check whether given value exists in generated items . We will check if 10 exists in generated numbers.

10 in range(20) 
#True

Check String

String value provides character array which creates string. Strings generally consist of words or meaningful values. We can check this values with in operator easily. We will check given string against word poftut .

mystr="I like to read poftut.com" 
"poftut" in mystr 
True
Check String
Check String

poftut exist in string named mystr

LEARN MORE  Linux tr Command Tutorial With Examples

Leave a Comment