Python Tutorial PDF
Document Details
Asif Bhat
Tags
Summary
This document is a Python tutorial that provides a fundamental introduction to Python programming. It explains essential concepts, including keywords, identifiers, comments, and statements. It also covers variable assignments and data types, such as integers, floats, and complex numbers.
Full Transcript
3/25/2021 Python - Jupyter Notebook Prepared by Asif Bhat Python Tutorial In : import sys import ke...
3/25/2021 Python - Jupyter Notebook Prepared by Asif Bhat Python Tutorial In : import sys import keyword import operator from datetime import datetime import os Keywords Keywords are the reserved words in Python and can't be used as an identifier In : print(keyword.kwlist) # List all Python Keywords ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'cl ass', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'fr om', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] In : len(keyword.kwlist) # Python contains 35 keywords Out: 35 Identifiers An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another. In : 1var = 10 # Identifier can't start with a digit File "", line 1 1var = 10 # Identifier can't start with a digit ^ SyntaxError: invalid syntax In : val2@ = 35 # Identifier can't use special symbols File "", line 1 val2@ = 35 # Identifier can't use special symbols ^ SyntaxError: invalid syntax localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 1/118 3/25/2021 Python - Jupyter Notebook In : import = 125 # Keywords can't be used as identifiers File "", line 1 import = 125 # Keywords can't be used as identifiers ^ SyntaxError: invalid syntax In : """ Correct way of defining an identifier (Identifiers can be a combination of letters in lowercase (a to z) or uppercase ( """ val2 = 10 In : val_ = 99 Comments in Python Comments can be used to explain the code for more readabilty. In : # Single line comment val1 = 10 In : # Multiple # line # comment val1 = 10 In : ''' Multiple line comment ''' val1 = 10 In : """ Multiple line comment """ val1 = 10 Statements Instructions that a Python interpreter can execute. localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 2/118 3/25/2021 Python - Jupyter Notebook In : # Single line statement p1 = 10 + 20 p1 Out: 30 In : # Single line statement p2 = ['a' , 'b' , 'c' , 'd'] p2 Out: ['a', 'b', 'c', 'd'] In : # Multiple line statement p1 = 20 + 30 \ + 40 + 50 +\ + 70 + 80 p1 Out: 290 In : # Multiple line statement p2 = ['a' , 'b' , 'c' , 'd' ] p2 Out: ['a', 'b', 'c', 'd'] Indentation Indentation refers to the spaces at the beginning of a code line. It is very important as Python uses indentation to indicate a block of code.If the indentation is not correct we will endup with IndentationError error. In : p = 10 if p == 10: print ('P is equal to 10') # correct indentation P is equal to 10 In : # if indentation is skipped we will encounter "IndentationError: expected an inde p = 10 if p == 10: print ('P is equal to 10') File "", line 3 print ('P is equal to 10') ^ IndentationError: expected an indented block localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 3/118 3/25/2021 Python - Jupyter Notebook In : for i in range(0,5): print(i) # correct indentation 0 1 2 3 4 In : # if indentation is skipped we will encounter "IndentationError: expected an inde for i in range(0,5): print(i) File "", line 2 print(i) ^ IndentationError: expected an indented block In : for i in range(0,5): print(i) # correct indentation but less readable 0 1 2 3 4 In : j=20 for i in range(0,5): print(i) # inside the for loop print(j) # outside the for loop 0 1 2 3 4 20 Docstrings 1) Docstrings provide a convenient way of associating documentation with functions, classes, methods or modules. 2) They appear right after the definition of a function, method, class, or module. In : def square(num): '''Square Function :- This function will return the square of a number''' return num**2 localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 4/118 3/25/2021 Python - Jupyter Notebook In : square(2) Out: 4 In : square.__doc__ # We can access the Docstring using __doc__ method Out: 'Square Function :- This function will return the square of a number' In : def evenodd(num): '''evenodd Function :- This function will test whether a numbr is Even or Odd if num % 2 == 0: print("Even Number") else: print("Odd Number") In : evenodd(3) Odd Number In : evenodd(2) Even Number In : evenodd.__doc__ Out: 'evenodd Function :- This function will test whether a numbr is Even or Odd' Variables A Python variable is a reserved memory location to store values.A variable is created the moment you first assign a value to it. In : p = 30 In : ''' id() function returns the “identity” of the object. The identity of an object - Is an integer - Guaranteed to be unique - Constant for this object during its lifetime. ''' id(p) Out: 140735029552432 In : hex(id(p)) # Memory address of the variable Out: '0x7fff6d71a530' localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 5/118 3/25/2021 Python - Jupyter Notebook In : p = 20 #Creates an integer object with value 20 and assigns the variable p to po q = 20 # Create new reference q which will point to value 20. p & q will be poin r = q # variable r will also point to the same location where p & q are pointing p , type(p), hex(id(p)) # Variable P is pointing to memory location '0x7fff6d71a3 Out: (20, int, '0x7fff6d71a3f0') In : q , type(q), hex(id(q)) Out: (20, int, '0x7fff6d71a3f0') In : r , type(r), hex(id(r)) Out: (20, int, '0x7fff6d71a3f0') In : p = 20 p = p + 10 # Variable Overwriting p Out: 30 Variable Assigment In : intvar = 10 # Integer variable floatvar = 2.57 # Float Variable strvar = "Python Language" # String variable print(intvar) print(floatvar) print(strvar) 10 2.57 Python Language localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 6/118 3/25/2021 Python - Jupyter Notebook Multiple Assignments In : intvar , floatvar , strvar = 10,2.57,"Python Language" # Using commas to separate print(intvar) print(floatvar) print(strvar) 10 2.57 Python Language In : p1 = p2 = p3 = p4 = 44 # All variables pointing to same value print(p1,p2,p3,p4) 44 44 44 44 Data Types Numeric In : val1 = 10 # Integer data type print(val1) print(type(val1)) # type of object print(sys.getsizeof(val1)) # size of integer object in bytes print(val1, " is Integer?", isinstance(val1, int)) # val1 is an instance of int c 10 28 10 is Integer? True In : val2 = 92.78 # Float data type print(val2) print(type(val2)) # type of object print(sys.getsizeof(val2)) # size of float object in bytes print(val2, " is float?", isinstance(val2, float)) # Val2 is an instance of float 92.78 24 92.78 is float? True In : val3 = 25 + 10j # Complex data type print(val3) print(type(val3)) # type of object print(sys.getsizeof(val3)) # size of float object in bytes print(val3, " is complex?", isinstance(val3, complex)) # val3 is an instance of c (25+10j) 32 (25+10j) is complex? True localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 7/118 3/25/2021 Python - Jupyter Notebook In : sys.getsizeof(int()) # size of integer object in bytes Out: 24 In : sys.getsizeof(float()) # size of float object in bytes Out: 24 In : sys.getsizeof(complex()) # size of complex object in bytes Out: 32 Boolean Boolean data type can have only two possible values true or false. In : bool1 = True In : bool2 = False In : print(type(bool1)) In : print(type(bool2)) In : isinstance(bool1, bool) Out: True In : bool(0) Out: False In : bool(1) Out: True In : bool(None) Out: False In : bool (False) Out: False Strings localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 8/118 3/25/2021 Python - Jupyter Notebook String Creation In : str1 = "HELLO PYTHON" print(str1) HELLO PYTHON In : mystr = 'Hello World' # Define string using single quotes print(mystr) Hello World In : mystr = "Hello World" # Define string using double quotes print(mystr) Hello World In : mystr = '''Hello World ''' # Define string using triple quotes print(mystr) Hello World In : mystr = """Hello World""" # Define string using triple quotes print(mystr) Hello World In : mystr = ('Happy ' 'Monday ' 'Everyone') print(mystr) Happy Monday Everyone In : mystr2 = 'Woohoo ' mystr2 = mystr2*5 mystr2 Out: 'Woohoo Woohoo Woohoo Woohoo Woohoo ' In : len(mystr2) # Length of string Out: 35 String Indexing localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 9/118 3/25/2021 Python - Jupyter Notebook In : str1 Out: 'HELLO PYTHON' In : str1 # First character in string "str1" Out: 'H' In : str1[len(str1)-1] # Last character in string using len function Out: 'N' In : str1[-1] # Last character in string Out: 'N' In : str1 #Fetch 7th element of the string Out: 'P' In : str1 Out: ' ' String Slicing In : str1[0:5] # String slicing - Fetch all characters from 0 to 5 index location excl Out: 'HELLO' In : str1[6:12] # String slicing - Retreive all characters between 6 - 12 index loc ex Out: 'PYTHON' In : str1[-4:] # Retreive last four characters of the string Out: 'THON' localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 10/118 3/25/2021 Python - Jupyter Notebook In : str1[-6:] # Retreive last six characters of the string Out: 'PYTHON' In : str1[:4] # Retreive first four characters of the string Out: 'HELL' In : str1[:6] # Retreive first six characters of the string Out: 'HELLO ' Update & Delete String In : str1 Out: 'HELLO PYTHON' In : #Strings are immutable which means elements of a string cannot be changed once th str1[0:5] = 'HOLAA' --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 1 #Strings are immutable which means elements of a string cannot be chang ed once they have been assigned. ----> 2 str1[0:5] = 'HOLAA' TypeError: 'str' object does not support item assignment In : del str1 # Delete a string print(srt1) --------------------------------------------------------------------------- NameError Traceback (most recent call last) in 1 del str1 # Delete a string ----> 2 print(srt1) NameError: name 'srt1' is not defined String concatenation In : # String concatenation s1 = "Hello" s2 = "Asif" s3 = s1 + s2 print(s3) HelloAsif localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 11/118 3/25/2021 Python - Jupyter Notebook In : # String concatenation s1 = "Hello" s2 = "Asif" s3 = s1 + " " + s2 print(s3) Hello Asif Iterating through a String In : mystr1 = "Hello Everyone" In : # Iteration for i in mystr1: print(i) H e l l o E v e r y o n e In : for i in enumerate(mystr1): print(i) (0, 'H') (1, 'e') (2, 'l') (3, 'l') (4, 'o') (5, ' ') (6, 'E') (7, 'v') (8, 'e') (9, 'r') (10, 'y') (11, 'o') (12, 'n') (13, 'e') localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 12/118 3/25/2021 Python - Jupyter Notebook In : list(enumerate(mystr1)) # Enumerate method adds a counter to an iterable and retu Out: [(0, 'H'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o'), (5, ' '), (6, 'E'), (7, 'v'), (8, 'e'), (9, 'r'), (10, 'y'), (11, 'o'), (12, 'n'), (13, 'e')] String Membership In : # String membership mystr1 = "Hello Everyone" print ('Hello' in mystr1) # Check whether substring "Hello" is present in string print ('Everyone' in mystr1) # Check whether substring "Everyone" is present in s print ('Hi' in mystr1) # Check whether substring "Hi" is present in string "mysrt True True False String Partitioning In : """ The partition() method searches for a specified string and splits the string into - The first element contains the part before the argument string. - The second element contains the argument string. - The third element contains the part after the argument string. """ str5 = "Natural language processing with Python and R and Java" L = str5.partition("and") print(L) ('Natural language processing with Python ', 'and', ' R and Java') localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 13/118 3/25/2021 Python - Jupyter Notebook In : """ The rpartition() method searches for the last occurence of the specified string a containing three elements. - The first element contains the part before the argument string. - The second element contains the argument string. - The third element contains the part after the argument string. """ str5 = "Natural language processing with Python and R and Java" L = str5.rpartition("and") print(L) ('Natural language processing with Python and R ', 'and', ' Java') String Functions In : mystr2 = " Hello Everyone " mystr2 Out: ' Hello Everyone ' In : mystr2.strip() # Removes white space from begining & end Out: 'Hello Everyone' In : mystr2.rstrip() # Removes all whitespaces at the end of the string Out: ' Hello Everyone' In : mystr2.lstrip() # Removes all whitespaces at the begining of the string Out: 'Hello Everyone ' In : mystr2 = "*********Hello Everyone***********All the Best**********" mystr2 Out: '*********Hello Everyone***********All the Best**********' In : mystr2.strip('*') # Removes all '*' characters from begining & end of the string Out: 'Hello Everyone***********All the Best' In : mystr2.rstrip('*') # Removes all '*' characters at the end of the string Out: '*********Hello Everyone***********All the Best' In : mystr2.lstrip('*') # Removes all '*' characters at the begining of the string Out: 'Hello Everyone***********All the Best**********' localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 14/118 3/25/2021 Python - Jupyter Notebook In : mystr2 = " Hello Everyone " In : mystr2.lower() # Return whole string in lowercase Out: ' hello everyone ' In : mystr2.upper() # Return whole string in uppercase Out: ' HELLO EVERYONE ' In : mystr2.replace("He" , "Ho") #Replace substring "He" with "Ho" Out: ' Hollo Everyone ' In : mystr2.replace(" " , "") # Remove all whitespaces using replace function Out: 'HelloEveryone' In : mystr5 = "one two Three one two two three" In : mystr5.count("one") # Number of times substring "one" occurred in string. Out: 2 In : mystr5.count("two") # Number of times substring "two" occurred in string. Out: 3 In : mystr5.startswith("one") # Return boolean value True if string starts with "one" Out: True In : mystr5.endswith("three") # Return boolean value True if string ends with "three" Out: True In : mystr4 = "one two three four one two two three five five six seven six seven one localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 15/118 3/25/2021 Python - Jupyter Notebook In : mylist = mystr4.split() # Split String into substrings mylist Out: ['one', 'two', 'three', 'four', 'one', 'two', 'two', 'three', 'five', 'five', 'six', 'seven', 'six', 'seven', 'one', 'one', 'one', 'ten', 'eight', 'ten', 'nine', 'eleven', 'ten', 'ten', 'nine'] In : # Combining string & numbers using format method item1 = 40 item2 = 55 item3 = 77 res = "Cost of item1 , item2 and item3 are {} , {} and {}" print(res.format(item1,item2,item3)) Cost of item1 , item2 and item3 are 40 , 55 and 77 In : # Combining string & numbers using format method item1 = 40 item2 = 55 item3 = 77 res = "Cost of item3 , item2 and item1 are {2} , {1} and {0}" print(res.format(item1,item2,item3)) Cost of item3 , item2 and item1 are 77 , 55 and 40 localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 16/118 3/25/2021 Python - Jupyter Notebook In : str2 = " WELCOME EVERYONE " str2 = str2.center(100) # center align the string using a specific character as t print(str2) WELCOME EVERYONE In : str2 = " WELCOME EVERYONE " str2 = str2.center(100,'*') # center align the string using a specific character print(str2) ***************************************** WELCOME EVERYONE ******************** ********************* In : str2 = " WELCOME EVERYONE " str2 = str2.rjust(50) # Right align the string using a specific character as the print(str2) WELCOME EVERYONE In : str2 = " WELCOME EVERYONE " str2 = str2.rjust(50,'*') # Right align the string using a specific character ('* print(str2) ******************************** WELCOME EVERYONE In : str4 = "one two three four five six seven" loc = str4.find("five") # Find the location of word 'five' in the string "str4" print(loc) 19 In : str4 = "one two three four five six seven" loc = str4.index("five") # Find the location of word 'five' in the string "str4" print(loc) 19 In : mystr6 = '123456789' print(mystr6.isalpha()) # returns True if all the characters in the text are lett print(mystr6.isalnum()) # returns True if a string contains only letters or numb print(mystr6.isdecimal()) # returns True if all the characters are decimals (0-9) print(mystr6.isnumeric()) # returns True if all the characters are numeric (0-9) False True True True localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 17/118 3/25/2021 Python - Jupyter Notebook In : mystr6 = 'abcde' print(mystr6.isalpha()) # returns True if all the characters in the text are lett print(mystr6.isalnum()) # returns True if a string contains only letters or numb print(mystr6.isdecimal()) # returns True if all the characters are decimals (0-9) print(mystr6.isnumeric()) # returns True if all the characters are numeric (0-9) True True False False In : mystr6 = 'abc12309' print(mystr6.isalpha()) # returns True if all the characters in the text are lett print(mystr6.isalnum()) # returns True if a string contains only letters or numb print(mystr6.isdecimal()) # returns True if all the characters are decimals (0-9) print(mystr6.isnumeric()) # returns True if all the characters are numeric (0-9) False True False False In : mystr7 = 'ABCDEF' print(mystr7.isupper()) # Returns True if all the characters are in upper case print(mystr7.islower()) # Returns True if all the characters are in lower case True False In : mystr8 = 'abcdef' print(mystr8.isupper()) # Returns True if all the characters are in upper case print(mystr8.islower()) # Returns True if all the characters are in lower case False True In : str6 = "one two three four one two two three five five six one ten eight ten nine loc = str6.rfind("one") # last occurrence of word 'one' in string "str6" print(loc) 51 In : loc = str6.rindex("one") # last occurrence of word 'one' in string "str6" print(loc) 51 In : txt = " abc def ghi " txt.rstrip() Out: ' abc def ghi' localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 18/118 3/25/2021 Python - Jupyter Notebook In : txt = " abc def ghi " txt.lstrip() Out: 'abc def ghi ' In : txt = " abc def ghi " txt.strip() Out: 'abc def ghi' Using Escape Character In : #Using double quotes in the string is not allowed. mystr = "My favourite TV Series is "Game of Thrones"" File "", line 2 mystr = "My favourite TV Series is "Game of Thrones"" ^ SyntaxError: invalid syntax In : #Using escape character to allow illegal characters mystr = "My favourite series is \"Game of Thrones\"" print(mystr) My favourite series is "Game of Thrones" List 1) List is an ordered sequence of items. 2) We can have different data types under a list. E.g we can have integer, float and string items in a same list. List Creation In : list1 = [] # Empty List In : print(type(list1)) In : list2 = [10,30,60] # List of integers numbers In : list3 = [10.77,30.66,60.89] # List of float numbers localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 19/118 3/25/2021 Python - Jupyter Notebook In : list4 = ['one','two' , "three"] # List of strings In : list5 = ['Asif', 25 ,[50, 100],[150, 90]] # Nested Lists In : list6 = [100, 'Asif', 17.765] # List of mixed data types In : list7 = ['Asif', 25 ,[50, 100],[150, 90] , {'John' , 'David'}] In : len(list6) #Length of list Out: 3 List Indexing In : list2 # Retreive first element of the list Out: 10 In : list4 # Retreive first element of the list Out: 'one' In : list4 # Nested indexing - Access the first character of the first list elem Out: 'o' In : list4[-1] # Last item of the list Out: 'three' In : list5[-1] # Last item of the list Out: [150, 90] List Slicing localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 20/118 3/25/2021 Python - Jupyter Notebook In : mylist = ['one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' , 'eight'] In : mylist[0:3] # Return all items from 0th to 3rd index location excluding the item Out: ['one', 'two', 'three'] In : mylist[2:5] # List all items from 2nd to 5th index location excluding the item at Out: ['three', 'four', 'five'] In : mylist[:3] # Return first three items Out: ['one', 'two', 'three'] In : mylist[:2] # Return first two items Out: ['one', 'two'] In : mylist[-3:] # Return last three items Out: ['six', 'seven', 'eight'] In : mylist[-2:] # Return last two items Out: ['seven', 'eight'] In : mylist[-1] # Return last item of the list Out: 'eight' In : mylist[:] # Return whole list Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] Add , Remove & Change Items In : mylist Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] In : mylist.append('nine') # Add an item to the end of the list mylist Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] In : mylist.insert(9,'ten') # Add item at index location 9 mylist Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 21/118 3/25/2021 Python - Jupyter Notebook In : mylist.insert(1,'ONE') # Add item at index location 1 mylist Out: ['one', 'ONE', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] In : mylist.remove('ONE') # Remove item "ONE" mylist Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] In : mylist.pop() # Remove last item of the list mylist Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] In : mylist.pop(8) # Remove item at index location 8 mylist Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] In : del mylist # Remove item at index location 7 mylist Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] In : # Change value of the string mylist = 1 mylist = 2 mylist = 3 mylist Out: [1, 2, 3, 'four', 'five', 'six', 'seven'] In : mylist.clear() # Empty List / Delete all items in the list mylist Out: [] localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 22/118 3/25/2021 Python - Jupyter Notebook In : del mylist # Delete the whole list mylist --------------------------------------------------------------------------- NameError Traceback (most recent call last) in 1 del mylist # Delete the whole list ----> 2 mylist NameError: name 'mylist' is not defined Copy List In : mylist = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', In : mylist1 = mylist # Create a new reference "mylist1" In : id(mylist) , id(mylist1) # The address of both mylist & mylist1 will be the same Out: (1537348392776, 1537348392776) In : mylist2 = mylist.copy() # Create a copy of the list In : id(mylist2) # The address of mylist2 will be different from mylist because mylist Out: 1537345955016 In : mylist = 1 In : mylist Out: [1, 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] In : mylist1 # mylist1 will be also impacted as it is pointing to the same list Out: [1, 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] In : mylist2 # Copy of list won't be impacted due to changes made on the original list Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] Join Lists In : list1 = ['one', 'two', 'three', 'four'] list2 = ['five', 'six', 'seven', 'eight'] In : list3 = list1 + list2 # Join two lists by '+' operator list3 Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 23/118 3/25/2021 Python - Jupyter Notebook In : list1.extend(list2) #Append list2 with list1 list1 Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] List Membership In : list1 Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] In : 'one' in list1 # Check if 'one' exist in the list Out: True In : 'ten' in list1 # Check if 'ten' exist in the list Out: False In : if 'three' in list1: # Check if 'three' exist in the list print('Three is present in the list') else: print('Three is not present in the list') Three is present in the list In : if 'eleven' in list1: # Check if 'eleven' exist in the list print('eleven is present in the list') else: print('eleven is not present in the list') eleven is not present in the list Reverse & Sort List In : list1 Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] In : list1.reverse() # Reverse the list list1 Out: ['eight', 'seven', 'six', 'five', 'four', 'three', 'two', 'one'] In : list1 = list1[::-1] # Reverse the list list1 Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 24/118 3/25/2021 Python - Jupyter Notebook In : mylist3 = [9,5,2,99,12,88,34] mylist3.sort() # Sort list in ascending order mylist3 Out: [2, 5, 9, 12, 34, 88, 99] In : mylist3 = [9,5,2,99,12,88,34] mylist3.sort(reverse=True) # Sort list in descending order mylist3 Out: [99, 88, 34, 12, 9, 5, 2] In : mylist4 = [88,65,33,21,11,98] sorted(mylist4) # Returns a new sorted list and doesn't change original li Out: [11, 21, 33, 65, 88, 98] In : mylist4 Out: [88, 65, 33, 21, 11, 98] Loop through a list In : list1 Out: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] In : for i in list1: print(i) one two three four five six seven eight In : for i in enumerate(list1): print(i) (0, 'one') (1, 'two') (2, 'three') (3, 'four') (4, 'five') (5, 'six') (6, 'seven') (7, 'eight') Count localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 25/118 3/25/2021 Python - Jupyter Notebook In : list10 =['one', 'two', 'three', 'four', 'one', 'one', 'two', 'three'] In : list10.count('one') # Number of times item "one" occurred in the list. Out: 3 In : list10.count('two') # Occurence of item 'two' in the list Out: 2 In : list10.count('four') #Occurence of item 'four' in the list Out: 1 All / Any The all() method returns: True - If all elements in a list are true False - If any element in a list is false The any() function returns True if any element in the list is True. If not, any() returns False. In : L1 = [1,2,3,4,0] In : all(L1) # Will Return false as one value is false (Value 0) Out: False In : any(L1) # Will Return True as we have items in the list with True value Out: True In : L2 = [1,2,3,4,True,False] In : all(L2) # Returns false as one value is false Out: False In : any(L2) # Will Return True as we have items in the list with True value Out: True In : L3 = [1,2,3,True] In : all(L3) # Will return True as all items in the list are True Out: True localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 26/118 3/25/2021 Python - Jupyter Notebook In : any(L3) # Will Return True as we have items in the list with True value Out: True List Comprehensions List Comprehensions provide an elegant way to create new lists. It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. In : mystring = "WELCOME" mylist = [ i for i in mystring ] # Iterating through a string Using List Comprehe mylist Out: ['W', 'E', 'L', 'C', 'O', 'M', 'E'] In : mylist1 = [ i for i in range(40) if i % 2 == 0] # Display all even numbers betwee mylist1 Out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38] In : mylist2 = [ i for i in range(40) if i % 2 == 1] # Display all odd numbers between mylist2 Out: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39] In : mylist3 = [num**2 for num in range(10)] # calculate square of all numbers between mylist3 Out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] In : # Multiple whole list by 10 list1 = [2,3,4,5,6,7,8] list1 = [i*10 for i in list1] list1 Out: [20, 30, 40, 50, 60, 70, 80] localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 27/118 3/25/2021 Python - Jupyter Notebook In : #List all numbers divisible by 3 , 9 & 12 using nested "if" with List Comprehensi mylist4 = [i for i in range(200) if i % 3 == 0 if i % 9 == 0 if i % 12 == 0] mylist4 Out: [0, 36, 72, 108, 144, 180] In : # Odd even test l1 = [print("{} is Even Number".format(i)) if i%2==0 else print("{} is odd number 0 is Even Number 1 is odd number 2 is Even Number 3 is odd number 4 is Even Number 5 is odd number 6 is Even Number 7 is odd number 8 is Even Number 9 is odd number In : # Extract numbers from a string mystr = "One 1 two 2 three 3 four 4 five 5 six 6789" numbers = [i for i in mystr if i.isdigit()] numbers Out: ['1', '2', '3', '4', '5', '6', '7', '8', '9'] In : # Extract letters from a string mystr = "One 1 two 2 three 3 four 4 five 5 six 6789" numbers = [i for i in mystr if i.isalpha()] numbers Out: ['O', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e', 'f', 'o', 'u', 'r', 'f', 'i', 'v', 'e', 's', 'i', 'x'] localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 28/118 3/25/2021 Python - Jupyter Notebook Tuples 1. Tuple is similar to List except that the objects in tuple are immutable which means we cannot change the elements of a tuple once assigned. 2. When we do not want to change the data over time, tuple is a preferred data type. 3. Iterating over the elements of a tuple is faster compared to iterating over a list. Tuple Creation In : tup1 = () # Empty tuple In : tup2 = (10,30,60) # tuple of integers numbers In : tup3 = (10.77,30.66,60.89) # tuple of float numbers In : tup4 = ('one','two' , "three") # tuple of strings In : tup5 = ('Asif', 25 ,(50, 100),(150, 90)) # Nested tuples In : tup6 = (100, 'Asif', 17.765) # Tuple of mixed data types In : tup7 = ('Asif', 25 ,[50, 100],[150, 90] , {'John' , 'David'} , (99,22,33)) In : len(tup7) #Length of list Out: 6 Tuple Indexing In : tup2 # Retreive first element of the tuple Out: 10 In : tup4 # Retreive first element of the tuple Out: 'one' In : tup4 # Nested indexing - Access the first character of the first tuple elem Out: 'o' In : tup4[-1] # Last item of the tuple Out: 'three' localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 29/118 3/25/2021 Python - Jupyter Notebook In : tup5[-1] # Last item of the tuple Out: (150, 90) Tuple Slicing In : mytuple = ('one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' , 'eight') In : mytuple[0:3] # Return all items from 0th to 3rd index location excluding the item Out: ('one', 'two', 'three') In : mytuple[2:5] # List all items from 2nd to 5th index location excluding the item a Out: ('three', 'four', 'five') In : mytuple[:3] # Return first three items Out: ('one', 'two', 'three') In : mytuple[:2] # Return first two items Out: ('one', 'two') In : mytuple[-3:] # Return last three items Out: ('six', 'seven', 'eight') In : mytuple[-2:] # Return last two items Out: ('seven', 'eight') In : mytuple[-1] # Return last item of the tuple Out: 'eight' In : mytuple[:] # Return whole tuple Out: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight') Remove & Change Items In : mytuple Out: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight') localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 30/118 3/25/2021 Python - Jupyter Notebook In : del mytuple # Tuples are immutable which means we can't DELETE tuple items --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 del mytuple TypeError: 'tuple' object doesn't support item deletion In : mytuple = 1 # Tuples are immutable which means we can't CHANGE tuple items --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 mytuple = 1 TypeError: 'tuple' object does not support item assignment In : del mytuple # Deleting entire tuple object is possible Loop through a tuple In : mytuple Out: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight') In : for i in mytuple: print(i) one two three four five six seven eight In : for i in enumerate(mytuple): print(i) (0, 'one') (1, 'two') (2, 'three') (3, 'four') (4, 'five') (5, 'six') (6, 'seven') (7, 'eight') localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 31/118 3/25/2021 Python - Jupyter Notebook Count In : mytuple1 =('one', 'two', 'three', 'four', 'one', 'one', 'two', 'three') In : mytuple1.count('one') # Number of times item "one" occurred in the tuple. Out: 3 In : mytuple1.count('two') # Occurence of item 'two' in the tuple Out: 2 In : mytuple1.count('four') #Occurence of item 'four' in the tuple Out: 1 Tuple Membership In : mytuple Out: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight') In : 'one' in mytuple # Check if 'one' exist in the list Out: True In : 'ten' in mytuple # Check if 'ten' exist in the list Out: False In : if 'three' in mytuple: # Check if 'three' exist in the list print('Three is present in the tuple') else: print('Three is not present in the tuple') Three is present in the tuple In : if 'eleven' in mytuple: # Check if 'eleven' exist in the list print('eleven is present in the tuple') else: print('eleven is not present in the tuple') eleven is not present in the tuple Index Position In : mytuple Out: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight') localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 32/118 3/25/2021 Python - Jupyter Notebook In : mytuple.index('one') # Index of first element equal to 'one' Out: 0 In : mytuple.index('five') # Index of first element equal to 'five' Out: 4 In : mytuple1 Out: ('one', 'two', 'three', 'four', 'one', 'one', 'two', 'three') In : mytuple1.index('one') # Index of first element equal to 'one' Out: 0 Sorting In : mytuple2 = (43,67,99,12,6,90,67) In : sorted(mytuple2) # Returns a new sorted list and doesn't change original tuple Out: [6, 12, 43, 67, 67, 90, 99] In : sorted(mytuple2, reverse=True) # Sort in descending order Out: [99, 90, 67, 67, 43, 12, 6] Sets 1) Unordered & Unindexed collection of items. 2) Set elements are unique. Duplicate elements are not allowed. 3) Set elements are immutable (cannot be changed). 4) Set itself is mutable. We can add or remove items from it. Set Creation In : myset = {1,2,3,4,5} # Set of numbers myset Out: {1, 2, 3, 4, 5} In : len(myset) #Length of the set Out: 5 localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 33/118 3/25/2021 Python - Jupyter Notebook In : my_set = {1,1,2,2,3,4,5,5} my_set # Duplicate elements are not allowed. Out: {1, 2, 3, 4, 5} In : myset1 = {1.79,2.08,3.99,4.56,5.45} # Set of float numbers myset1 Out: {1.79, 2.08, 3.99, 4.56, 5.45} In : myset2 = {'Asif' , 'John' , 'Tyrion'} # Set of Strings myset2 Out: {'Asif', 'John', 'Tyrion'} In : myset3 = {10,20, "Hola", (11, 22, 32)} # Mixed datatypes myset3 Out: {(11, 22, 32), 10, 20, 'Hola'} In : myset3 = {10,20, "Hola", [11, 22, 32]} # set doesn't allow mutable items like lis myset3 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 myset3 = {10,20, "Hola", [11, 22, 32]} # set doesn't allow mutable item s like lists 2 myset3 TypeError: unhashable type: 'list' In : myset4 = set() # Create an empty set print(type(myset4)) In : my_set1 = set(('one' , 'two' , 'three' , 'four')) my_set1 Out: {'four', 'one', 'three', 'two'} Loop through a Set localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 34/118 3/25/2021 Python - Jupyter Notebook In : myset = {'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'} for i in myset: print(i) eight one seven three five two six four In : for i in enumerate(myset): print(i) (0, 'eight') (1, 'one') (2, 'seven') (3, 'three') (4, 'five') (5, 'two') (6, 'six') (7, 'four') Set Membership In : myset Out: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} In : 'one' in myset # Check if 'one' exist in the set Out: True In : 'ten' in myset # Check if 'ten' exist in the set Out: False In : if 'three' in myset: # Check if 'three' exist in the set print('Three is present in the set') else: print('Three is not present in the set') Three is present in the set In : if 'eleven' in myset: # Check if 'eleven' exist in the list print('eleven is present in the set') else: print('eleven is not present in the set') eleven is not present in the set localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 35/118 3/25/2021 Python - Jupyter Notebook Add & Remove Items In : myset Out: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} In : myset.add('NINE') # Add item to a set using add() method myset Out: {'NINE', 'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} In : myset.update(['TEN' , 'ELEVEN' , 'TWELVE']) # Add multiple item to a set using u myset Out: {'ELEVEN', 'NINE', 'TEN', 'TWELVE', 'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} In : myset.remove('NINE') # remove item in a set using remove() method myset Out: {'ELEVEN', 'TEN', 'TWELVE', 'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} In : myset.discard('TEN') # remove item from a set using discard() method myset Out: {'ELEVEN', 'TWELVE', 'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 36/118 3/25/2021 Python - Jupyter Notebook In : myset.clear() # Delete all items in a set myset Out: set() In : del myset # Delete the set object myset --------------------------------------------------------------------------- NameError Traceback (most recent call last) in 1 del myset ----> 2 myset NameError: name 'myset' is not defined Copy Set In : myset = {'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'} myset Out: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} In : myset1 = myset # Create a new reference "myset1" myset1 Out: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} In : id(myset) , id(myset1) # The address of both myset & myset1 will be the same as Out: (1537349033320, 1537349033320) In : my_set = myset.copy() # Create a copy of the list my_set Out: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} In : id(my_set) # The address of my_set will be different from myset because my_set is Out: 1537352902024 In : myset.add('nine') myset Out: {'eight', 'five', 'four', 'nine', 'one', 'seven', 'six', 'three', 'two'} In : myset1 # myset1 will be also impacted as it is pointing to the same Set Out: {'eight', 'five', 'four', 'nine', 'one', 'seven', 'six', 'three', 'two'} In : my_set # Copy of the set won't be impacted due to changes made on the original Se Out: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 37/118 3/25/2021 Python - Jupyter Notebook Set Operation Union In : A = {1,2,3,4,5} B = {4,5,6,7,8} C = {8,9,10} In : A | B # Union of A and B (All elements from both sets. NO DUPLICATES) Out: {1, 2, 3, 4, 5, 6, 7, 8} In : A.union(B) # Union of A and B Out: {1, 2, 3, 4, 5, 6, 7, 8} In : A.union(B, C) # Union of A, B and C. Out: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} In : """ Updates the set calling the update() method with union of A , B & C. For below example Set A will be updated with union of A,B & C. """ A.update(B,C) A Out: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Intersection In : A = {1,2,3,4,5} B = {4,5,6,7,8} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 38/118 3/25/2021 Python - Jupyter Notebook In : A & B # Intersection of A and B (Common items in both sets) Out: {4, 5} In : A.intersection(B) Intersection of A and B File "", line 1 A.intersection(B) Intersection of A and B ^ SyntaxError: invalid syntax In : """ Updates the set calling the intersection_update() method with the intersection of For below example Set A will be updated with the intersection of A & B. """ A.intersection_update(B) A Out: {4, 5} Difference In : A = {1,2,3,4,5} B = {4,5,6,7,8} In : A - B # set of elements that are only in A but not in B Out: {1, 2, 3} In : A.difference(B) # Difference of sets Out: {1, 2, 3} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 39/118 3/25/2021 Python - Jupyter Notebook In : B- A # set of elements that are only in B but not in A Out: {6, 7, 8} In : B.difference(A) Out: {6, 7, 8} In : """ Updates the set calling the difference_update() method with the difference of set For below example Set B will be updated with the difference of B & A. """ B.difference_update(A) B Out: {6, 7, 8} Symmetric Difference In : A = {1,2,3,4,5} B = {4,5,6,7,8} In : A ^ B # Symmetric difference (Set of elements in A and B but not in both. "EXCLUD Out: {1, 2, 3, 6, 7, 8} In : A.symmetric_difference(B) # Symmetric difference of sets Out: {1, 2, 3, 6, 7, 8} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 40/118 3/25/2021 Python - Jupyter Notebook In : """ Updates the set calling the symmetric_difference_update() method with the symmetr For below example Set A will be updated with the symmetric difference of A & B. """ A.symmetric_difference_update(B) A Out: {1, 2, 3, 6, 7, 8} Subset , Superset & Disjoint In : A = {1,2,3,4,5,6,7,8,9} B = {3,4,5,6,7,8} C = {10,20,30,40} In : B.issubset(A) # Set B is said to be the subset of set A if all elements of B are Out: True In : A.issuperset(B) # Set A is said to be the superset of set B if all elements of B Out: True In : C.isdisjoint(A) # Two sets are said to be disjoint sets if they have no common el Out: True In : B.isdisjoint(A) # Two sets are said to be disjoint sets if they have no common el Out: False Other Builtin functions localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 41/118 3/25/2021 Python - Jupyter Notebook In : A Out: {1, 2, 3, 4, 5, 6, 7, 8, 9} In : sum(A) Out: 45 In : max(A) Out: 9 In : min(A) Out: 1 In : len(A) Out: 9 In : list(enumerate(A)) Out: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)] In : D= sorted(A,reverse=True) D Out: [9, 8, 7, 6, 5, 4, 3, 2, 1] In : sorted(D) Out: [1, 2, 3, 4, 5, 6, 7, 8, 9] Dictionary Dictionary is a mutable data type in Python. A python dictionary is a collection of key and value pairs separated by a colon (:) & enclosed in curly braces {}. Keys must be unique in a dictionary, duplicate values are allowed. localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 42/118 3/25/2021 Python - Jupyter Notebook Create Dictionary In : mydict = dict() # empty dictionary mydict Out: {} In : mydict = {} # empty dictionary mydict Out: {} In : mydict = {1:'one' , 2:'two' , 3:'three'} # dictionary with integer keys mydict Out: {1: 'one', 2: 'two', 3: 'three'} In : mydict = dict({1:'one' , 2:'two' , 3:'three'}) # Create dictionary using dict() mydict Out: {1: 'one', 2: 'two', 3: 'three'} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 43/118 3/25/2021 Python - Jupyter Notebook In : mydict = {'A':'one' , 'B':'two' , 'C':'three'} # dictionary with character keys mydict Out: {'A': 'one', 'B': 'two', 'C': 'three'} In : mydict = {1:'one' , 'A':'two' , 3:'three'} # dictionary with mixed keys mydict Out: {1: 'one', 'A': 'two', 3: 'three'} In : mydict.keys() # Return Dictionary Keys using keys() method Out: dict_keys([1, 'A', 3]) In : mydict.values() # Return Dictionary Values using values() method Out: dict_values(['one', 'two', 'three']) In : mydict.items() # Access each key-value pair within a dictionary Out: dict_items([(1, 'one'), ('A', 'two'), (3, 'three')]) In : mydict = {1:'one' , 2:'two' , 'A':['asif' , 'john' , 'Maria']} # dictionary with mydict Out: {1: 'one', 2: 'two', 'A': ['asif', 'john', 'Maria']} In : mydict = {1:'one' , 2:'two' , 'A':['asif' , 'john' , 'Maria'], 'B':('Bat' , 'cat mydict Out: {1: 'one', 2: 'two', 'A': ['asif', 'john', 'Maria'], 'B': ('Bat', 'cat', 'hat')} In : mydict = {1:'one' , 2:'two' , 'A':{'Name':'asif' , 'Age' :20}, 'B':('Bat' , 'cat mydict Out: {1: 'one', 2: 'two', 'A': {'Name': 'asif', 'Age': 20}, 'B': ('Bat', 'cat', 'hat')} In : keys = {'a' , 'b' , 'c' , 'd'} mydict3 = dict.fromkeys(keys) # Create a dictionary from a sequence of keys mydict3 Out: {'c': None, 'd': None, 'a': None, 'b': None} In : keys = {'a' , 'b' , 'c' , 'd'} value = 10 mydict3 = dict.fromkeys(keys , value) # Create a dictionary from a sequence of k mydict3 Out: {'c': 10, 'd': 10, 'a': 10, 'b': 10} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 44/118 3/25/2021 Python - Jupyter Notebook In : keys = {'a' , 'b' , 'c' , 'd'} value = [10,20,30] mydict3 = dict.fromkeys(keys , value) # Create a dictionary from a sequence of k mydict3 Out: {'c': [10, 20, 30], 'd': [10, 20, 30], 'a': [10, 20, 30], 'b': [10, 20, 30]} In : value.append(40) mydict3 Out: {'c': [10, 20, 30, 40], 'd': [10, 20, 30, 40], 'a': [10, 20, 30, 40], 'b': [10, 20, 30, 40]} Accessing Items In : mydict = {1:'one' , 2:'two' , 3:'three' , 4:'four'} mydict Out: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} In : mydict # Access item using key Out: 'one' In : mydict.get(1) # Access item using get() method Out: 'one' In : mydict1 = {'Name':'Asif' , 'ID': 74123 , 'DOB': 1991 , 'job' :'Analyst'} mydict1 Out: {'Name': 'Asif', 'ID': 74123, 'DOB': 1991, 'job': 'Analyst'} In : mydict1['Name'] # Access item using key Out: 'Asif' In : mydict1.get('job') # Access item using get() method Out: 'Analyst' Add, Remove & Change Items In : mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Address' : 'Hilsinki'} mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Hilsinki'} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 45/118 3/25/2021 Python - Jupyter Notebook In : mydict1['DOB'] = 1992 # Changing Dictionary Items mydict1['Address'] = 'Delhi' mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1992, 'Address': 'Delhi'} In : dict1 = {'DOB':1995} mydict1.update(dict1) mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1995, 'Address': 'Delhi'} In : mydict1['Job'] = 'Analyst' # Adding items in the dictionary mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1995, 'Address': 'Delhi', 'Job': 'Analyst'} In : mydict1.pop('Job') # Removing items in the dictionary using Pop method mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1995, 'Address': 'Delhi'} In : mydict1.popitem() # A random item is removed Out: ('Address', 'Delhi') In : mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1995} In : del[mydict1['ID']] # Removing item using del method mydict1 Out: {'Name': 'Asif', 'DOB': 1995} In : mydict1.clear() # Delete all items of the dictionary using clear method mydict1 Out: {} In : del mydict1 # Delete the dictionary object mydict1 --------------------------------------------------------------------------- NameError Traceback (most recent call last) in 1 del mydict1 # Delete the dictionary object ----> 2 mydict1 NameError: name 'mydict1' is not defined localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 46/118 3/25/2021 Python - Jupyter Notebook Copy Dictionary In : mydict = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Address' : 'Hilsinki'} mydict Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Hilsinki'} In : mydict1 = mydict # Create a new reference "mydict1" In : id(mydict) , id(mydict1) # The address of both mydict & mydict1 will be the same Out: (1537346312776, 1537346312776) In : mydict2 = mydict.copy() # Create a copy of the dictionary In : id(mydict2) # The address of mydict2 will be different from mydict because mydict Out: 1537345875784 In : mydict['Address'] = 'Mumbai' In : mydict Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Mumbai'} In : mydict1 # mydict1 will be also impacted as it is pointing to the same dictionary Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Mumbai'} In : mydict2 # Copy of list won't be impacted due to the changes made in the original Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Hilsinki'} Loop through a Dictionary In : mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Address' : 'Hilsinki' , ' mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Hilsinki', 'Job': 'Analyst'} In : for i in mydict1: print(i , ':' , mydict1[i]) # Key & value pair Name : Asif ID : 12345 DOB : 1991 Address : Hilsinki Job : Analyst localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 47/118 3/25/2021 Python - Jupyter Notebook In : for i in mydict1: print(mydict1[i]) # Dictionary items Asif 12345 1991 Hilsinki Analyst Dictionary Membership In : mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Job': 'Analyst'} mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Job': 'Analyst'} In : 'Name' in mydict1 # Test if a key is in a dictionary or not. Out: True In : 'Asif' in mydict1 # Membership test can be only done for keys. Out: False In : 'ID' in mydict1 Out: True In : 'Address' in mydict1 Out: False All / Any The all() method returns: True - If all all keys of the dictionary are true False - If any key of the dictionary is false The any() function returns True if any key of the dictionary is True. If not, any() returns False. In : mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Job': 'Analyst'} mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Job': 'Analyst'} In : all(mydict1) # Will Return false as one value is false (Value 0) Out: True localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 48/118 3/25/2021 Python - Jupyter Notebook In : any(mydict1) # Will Return True as we have items in the dictionary with True val Out: True In : mydict1 = 'test1' mydict1 Out: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Job': 'Analyst', 0: 'test1'} In : all(mydict1) # Returns false as one value is false Out: False In : any(mydict1) # Will Return True as we have items in the dictionary with True val Out: True Dictionary Comprehension In : double = {i:i*2 for i in range(10)} #double each value using dict comprehension double Out: {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18} In : square = {i:i**2 for i in range(10)} square Out: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} In : key = ['one' , 'two' , 'three' , 'four' , 'five'] value = [1,2,3,4,5] mydict = {k:v for (k,v) in zip(key,value)} # using dict comprehension to create d mydict Out: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 49/118 3/25/2021 Python - Jupyter Notebook In : mydict1 = {'a':10 , 'b':20 , 'c':30 , 'd':40 , 'e':50} mydict1 = {k:v/10 for (k,v) in mydict1.items()} # Divide all values in a dictiona mydict1 Out: {'a': 1.0, 'b': 2.0, 'c': 3.0, 'd': 4.0, 'e': 5.0} In : str1 = "Natural Language Processing" mydict2 = {k:v for (k,v) in enumerate(str1)} # Store enumerated values in a dicti mydict2 Out: {0: 'N', 1: 'a', 2: 't', 3: 'u', 4: 'r', 5: 'a', 6: 'l', 7: ' ', 8: 'L', 9: 'a', 10: 'n', 11: 'g', 12: 'u', 13: 'a', 14: 'g', 15: 'e', 16: ' ', 17: 'P', 18: 'r', 19: 'o', 20: 'c', 21: 'e', 22: 's', 23: 's', 24: 'i', 25: 'n', 26: 'g'} localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 50/118 3/25/2021 Python - Jupyter Notebook In : str1 = "abcdefghijklmnopqrstuvwxyz" mydict3 = {i:i.upper() for i in str1} # Lower to Upper Case mydict3 Out: {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L', 'm': 'M', 'n': 'N', 'o': 'O', 'p': 'P', 'q': 'Q', 'r': 'R', 's': 'S', 't': 'T', 'u': 'U', 'v': 'V', 'w': 'W', 'x': 'X', 'y': 'Y', 'z': 'Z'} Word Frequency using dictionary In : mystr4 = "one two three four one two two three five five six seven six seven one localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 51/118 3/25/2021 Python - Jupyter Notebook In : mylist = mystr4.split() # Split String into substrings mylist Out: ['one', 'two', 'three', 'four', 'one', 'two', 'two', 'three', 'five', 'five', 'six', 'seven', 'six', 'seven', 'one', 'one', 'one', 'ten', 'eight', 'ten', 'nine', 'eleven', 'ten', 'ten', 'nine'] In : mylist1 = set(mylist) # Unique values in a list mylist1 = list (mylist1) mylist1 Out: ['nine', 'one', 'eight', 'two', 'seven', 'ten', 'four', 'five', 'three', 'eleven', 'six'] localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 52/118 3/25/2021 Python - Jupyter Notebook In : # Calculate frequenct of each word count1 = * len(mylist1) mydict5 = dict() for i in range(len(mylist1)): for j in range(len(mylist)): if mylist1[i] == mylist[j]: count1[i] += 1 mydict5[mylist1[i]] = count1[i] print(mydict5) {'nine': 2, 'one': 5, 'eight': 1, 'two': 3, 'seven': 2, 'ten': 4, 'four': 1, 'f ive': 2, 'three': 2, 'eleven': 1, 'six': 2} Operators Operators are special symbols in Python which are used to perform operations on variables/values. Arithmetic Operators localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 53/118 3/25/2021 Python - Jupyter Notebook In : a = 5 b = 2 x = 'Asif' y = 'Bhat' # Addition c = a + b print('Addition of {} and {} will give :- {}\n'.format(a,b,c)) #Concatenate string using plus operator z = x+y print ('Concatenate string \'x\' and \'y\' using \'+\' operaotr :- {}\n'.format(z # Subtraction c = a - b print('Subtracting {} from {} will give :- {}\n'.format(b,a,c)) # Multiplication c = a * b print('Multiplying {} and {} will give :- {}\n'.format(a,b,c)) # Division c = a / b print('Dividing {} by {} will give :- {}\n'.format(a,b,c)) # Modulo of both number c = a % b print('Modulo of {} , {} will give :- {}\n'.format(a,b,c)) # Power c = a ** b print('{} raised to the power {} will give :- {}\n'.format(a,b,c)) # Division(floor) c = a // b print('Floor division of {} by {} will give :- {}\n'.format(a,b,c)) Addition of 5 and 2 will give :- 7 Concatenate string 'x' and 'y' using '+' operaotr :- AsifBhat Subtracting 2 from 5 will give :- 3 Multiplying 5 and 2 will give :- 10 Dividing 5 by 2 will give :- 2.5 Modulo of 5 , 2 will give :- 1 5 raised to the power 2 will give :- 25 Floor division of 5 by 2 will give :- 2 localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 54/118 3/25/2021 Python - Jupyter Notebook Comparison Operators Comparison operators are used to compare values. In : x = 20 y = 30 print('Is x greater than y :- ',x>y) print('\nIs x less than y :- ',x=y) print('\nIs x less than or equal to y :- ',x>2)) print('Bitwise left shift operation - {}'.format(x 10 myfunc2() in myfunc2() 5 6 def myfunc2(): ----> 7 print(var2) # Value 100 will be displayed due to global scope of va r1 8 9 myfunc1() NameError: name 'var2' is not defined In : var1 = 100 # Variable with Global scope. def myfunc(): var1 = 99 # Local scope print(var1) myfunc() print(var1) # The original value of var1 (100) will be retained due to global sco 99 100 In : list1 = [11,22,33,44,55] def myfunc(list1): del list1 print('"List1" before calling the function:- ',list1) myfunc(list1) # Pass by reference (Any change in the parameter within the functi print('"List1" after calling the function:- ',list1) "List1" before calling the function:- [11, 22, 33, 44, 55] "List1" after calling the function:- [22, 33, 44, 55] localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 63/118 3/25/2021 Python - Jupyter Notebook In : list1 = [11,22,33,44,55] def myfunc(list1): list1.append(100) print('"List1" before calling the function:- ',list1) myfunc(list1) # Pass by reference (Any change in the parameter within the functi print('"List1" after calling the function:- ',list1) "List1" before calling the function:- [11, 22, 33, 44, 55] "List1" after calling the function:- [11, 22, 33, 44, 55, 100] In : list1 = [11,22,33,44,55] def myfunc(list1): list1 = [10,100,1000,10000] # link of 'list1' with previous object is broken print('"List1" before calling the function:- ',list1) myfunc(list1) # Pass by reference (Any change in the parameter within the functi print('"List1" after calling the function:- ',list1) "List1" before calling the function:- [11, 22, 33, 44, 55] "List1" after calling the function:- [11, 22, 33, 44, 55] In : def swap(a,b): temp = a a = b # link of 'a' with previous object is broken now as new object is b = temp # link of 'b' with previous object is broken now as new object is a = 10 b = 20 swap(a,b) a,b Out: (10, 20) In : def factorial(num): # Calculate factorial of a number using recursive function c if num 1 os.remove("test3.txt") FileNotFoundError: [WinError 2] The system cannot find the file specified: 'tes t3.txt' In : os.rmdir('folder1/') # Delete folder In : os.rmdir('folder1/') --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) in ----> 1 os.rmdir('folder1/') FileNotFoundError: [WinError 2] The system cannot find the file specified: 'fol der1/' Error & Exception Handling Python has many built-in exceptions (ArithmeticError, ZeroDivisionError, EOFError, IndexError, KeyError, SyntaxError, IndentationError, FileNotFoundError etc) that are raised when your program encounters an error. localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 112/118 3/25/2021 Python - Jupyter Notebook When the exception occurs Python interpreter stops the current process and passes it to the calling process until it is handled. If exception is not handled the program will crash. Exceptions in python can be handled using a try statement. The try block lets you test a block of code for errors. The block of code which can raise an exception is placed inside the try clause. The code that will handle the exceptions is written in the except clause. The finally code block will execute regardless of the result of the try and except blocks. We can also use the else keyword to define a block of code to be executed if no exceptions were raised. Python also allows us to create our own exceptions that can be raised from the program using the raise keyword and caught using the except clause. We can define what kind of error to raise, and the text to print to the user. localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 113/118 3/25/2021 Python - Jupyter Notebook In : try: print(100/0) # ZeroDivisionError will be encountered here. So the control wil except: print(sys.exc_info() , 'Exception occured') # This statement will be execu else: print('No exception occurred') # This will be skipped as code block inside tr finally: print('Run this block of code always') # This will be always executed division by zero Exception occured Run this block of code always In : try: print(x) # NameError exception will be encountered as variable x is not defi except: print('Variable x is not defined') Variable x is not defined localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 114/118 3/25/2021 Python - Jupyter Notebook In : try: os.remove("test3.txt") # FileNotFoundError will be encountered as "test3.txt" except: # Below statement will be executed as exception occur print("BELOW EXCEPTION OCCURED") print(sys.exc_info()) else: print('\nNo exception occurred') finally: print('\nRun this block of code always') BELOW EXCEPTION OCCURED [WinError 2] The system cannot find the file specified: 'test3.txt' Run this block of code always In : # Handling specific exceptions try: x = int(input('Enter first number :- ')) y = int(input('Enter first number :- ')) # If input entered is non-zero the print(x/y) os.remove("test3.txt") except NameError: print('NameError exception occurred') except FileNotFoundError: print('FileNotFoundError exception occurred') except ZeroDivisionError: print('ZeroDivisionError exception occurred') Enter first number :- 12 Enter first number :- 13 0.9230769230769231 FileNotFoundError exception occurred localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 115/118 3/25/2021 Python - Jupyter Notebook In : # Handling specific exceptions try: x = int(input('Enter first number :- ')) y = int(input('Enter first number :- ')) # If the input entered is zero the print(x/y) os.remove("test3.txt") except NameError: print('NameError exception occurred') except FileNotFoundError: print('FileNotFoundError exception occurred') except ZeroDivisionError: print('ZeroDivisionError exception occurred') Enter first number :- 10 Enter first number :- 0 ZeroDivisionError exception occurred In : try: x = int(input('Enter first number :- ')) if x > 50: raise ValueError(x) # If value of x is greater than 50 ValueError excepti except: print(sys.exc_info()) Enter first number :- 100 Built-in Exceptions In : # OverflowError - This exception is raised when the result of a numeric calculati try: import math print(math.exp(1000)) except OverflowError: print (sys.exc_info()) else: print ("Success, no error!") (, OverflowError('math range error'), ) localhost:8889/notebooks/Documents/GitHub/Public/Python/Python.ipynb 116/118 3/25/2021 Python - Jupyter Notebook In : # ZeroDivisionError - This exception is raised when the second operator in a divi try: x = int(input('Enter first number :- ')) y = int(input('Enter first number :- ')) print(x/y) except ZeroDivisionError: print('ZeroDivisionError exception occurred') Enter first number :- 100 Enter first number :- 0 ZeroDivisionError exception occurred In : # NameError - This exception is raised when a variable does not exist try: print(x1) except NameError: print('NameError exception occurred') NameError exception occurred In : # AssertionError - This exception is raised when an assert statement fails try: a = 50 b = "Asif" assert a == b except AssertionError: print ("Assertion Exception Raised.") Assertion Exception Raised. In : # ModuleNotFoundError - This exception is raised when an imported module does not try: import MyModule except ModuleNotFoundError: print ("ModuleNotFoundError Exception Raised.") Mod