0% found this document useful (0 votes)
7 views87 pages

02 Python Notes

The document explains literals in Python, categorizing them into five types: integer, string, float, boolean, and date literals. It also discusses identifiers (variables) and their rules for naming in Python, emphasizing that variables can store different types of literals. Additionally, it outlines the various data types in Python, including fundamental, sequence, collection, and NoneType categories, with specific examples for each type.

Uploaded by

Kumaran K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views87 pages

02 Python Notes

The document explains literals in Python, categorizing them into five types: integer, string, float, boolean, and date literals. It also discusses identifiers (variables) and their rules for naming in Python, emphasizing that variables can store different types of literals. Additionally, it outlines the various data types in Python, including fundamental, sequence, collection, and NoneType categories, with specific examples for each type.

Uploaded by

Kumaran K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 87

Literals and Its Types

=>A Literal is nothing but a value passing as input to the program.


=>In Python Programming, Primarily, Literals are classified into 5 types. They are
1. Integer Literals------Example---> 234 567 23
2. String Literals--------Examples--->"Python", "Rossum", "Ram"
3. Float Literals---------Examples----> 34.56 4.5 99.99 0.999
4. Boolean Literals-----Examples-----> True False
5. Date Literals-----------Examples: ----> 29-08-2022, 17-08-2022...etc
--------------------------------------------------------------------------------------------------------------------
Identifiers or Variables
=>We know that all types of Literals are stored in main memory by allocating Sufficient amount of
Memory with help of Data Types.
=>To Process the Data / Literals stored in main memory, we must give distinct names to the created
memory space and these distinct names make us to identify the values and they are also called
IDENTIFIERS.
=>During Program Execution IDENTIFIER Values can be changed / Varying and hence IDENTIFIERs
are called VARIABLES.
=>Hence All Types of LITERALS Must Be stored in the form of VARIABLES.
=>In Python Programming All Variables are called Objects.
---------------------------------
Definition of Variable
=>A Variable is one of the Identifier whose value(s) can be changed during Program execution.
=>In Programming Language to do any data processing, we must use Variables / Objects (Python).
------------------------------------------------------------------------------------------------------------------------
Rules for Using Variables or Identifiers in Python Program
=>To Use Variables in Python Programming, we use the following Rules.

1. A Variable Name is a combination of Alphabets, Digits and a Special Symbol Under Score (_).
2. First Letter of the Variable Names must start Either with Alphabet or Special Symbol Under Score
(_)
Examples:
sal=23(valid) $sal=45(Invalid) @name="python"(Invalid) -sal=45(Invalid)
2sal=56(Invalid) 456=3.4(Invalid) _sal_=4(valid) _=56(valid)
__=5.6(valid) --=45----invalid

3. Within the variable name, no special symbols are allowed except Under Score (_)
Examples:
tot sal=45(Invalid) tot_marks=456(valid) tot#sal=56(NameError)

4. No Keywords to be used as Variable Names (bcoz Keywords are the Reserved Words and they give
special Meaning to the compilers).
Example:
if=45(Invalid) else=67(invalid) for=4.5(Invalid) if1=56(Valid)
_else=67(valid) _for_=5.6(valid)

Note: All Class Name can be used as Variable Names bcoz Class Names are not Keywords

5. All Variable Name are Case Sensitive


Examples:

age=99(Valid) AGE=98(Valid) Age=97(Valid) aGe=96(Valid)


1
print(age,AGE,Age,aGe)->99 98 97 96
a=12 A=13 print(a,A)-> 12 13

Data Types in Python


=>The Purpose of Data Types in Python is that " To allocate Sufficient amount of memory space for
storing inputs in main memory of computer".
=>In Python Programming, we have 14 Data Types and They are Classified into 6 types.

I. Fundamental Category Data Types


1. int 2. float 3. bool 4. complex
II. Sequence Category Data Types
1. str 2. bytes 3. bytearray 4. range
III. List Category Data Types (Collections Data Types or Data Structures)
1. list 2. tuple
IV. Set Category Data Types (Collections Data Types or Data Structures)
1. set 2. frozenset
VI. Dict Category Data Types (Collections Data Types or Data Structures)
1. dict
VI. NoneType Category Data Type
1. NoneType

1. Fundamental Category Data Types


=>The purpose of Fundamental Category Data Types is that " To store Single Value".
=>In Python Programming, we have 4 data types in Fundamental Category. They are

1. int 2. Float 3. bool 4. Complex

1. int
Properties
=>'int' is one of the pre-defined class and treated as Fundamental Data Type.
=>The purpose of int data type is that " To store Integer Data or Whole Numbers or Integral
Values (Numbers or digits without decimal Places) and Different Number System data".
Examples:
Python Instructions Output
>>> a=100 >>> b=123 >>> c=a+b >>> print(a,type(a))->100 <class 'int'>
>>> print(b,type(b))->123 <class 'int'> >>> print(c,type(c))->223 <class 'int'>
-----------------------------------------------------------------------------------------------------------
=>with int data type we can also Store Different types of Number Systems Values.
=>In Programming languages, we have 4 Types of Number Systems. They are
1. Decimal Number System (default) 2. Binary Number System
3. Octal Number System 4. Hexa Decimal Number System
----------------------------------------------------------------------------------------------------------------
1. Decimal Number System (default)
=>This is one of the default number System.
=>This Number System Contains
Digits: 0 1 2 3 4 5 6 7 8 9 ------Total Digits =10 Base : 10
=>All Base 10 Literals are called Integer Data.
=>By default python Execution Environment always displays the result in the form decimal number
System.
----------------------------------------------------------------------------------------------------------------
2. Binary Number System
2
=>This Number System Contains Digits: 0 1 ------Total Digits =2 Base : 2
=>All Base 2 Literals are called Binary Data.
=>To Store Binary Data in python environment, The Binary Data Must be preceded by a letter ‘b' / 'B'
=>Syntax: varname=0b Binary data (OR) varname=0B Binary data
=>When we store the Binary data in python environment, python Execution Environment
converts automatically into decimal number System data.
Examples:
------------------------
>>> a=0b1010 >>> print(a,type(a))->10 <class 'int'>
>>> bin(10)->'0b1010'
>>> a=0B1111 >>> print(a,type(a))->15 <class 'int'>
>>> a=0b10120->SyntaxError: invalid digit '2' in binary literal
----------------------------------------------------------------------------------------------------------------
3. Octal Number System
=>This Number System Contains Digits: 0 1 2 3 4 5 6 7 ------Total Digits =8 Base : 8
=>All Base 8 Literals are called Octal Data.
=>To Store Octal Data in python environment, The Octal Data Must be preceded by a letter
'o' or 'O'
=>Syntax: varname=0o Octal data (OR) varname=0O Octal data
=>When we store the Octal data in python environment, python Execution Environment converts
automatically into decimal number System data.
Examples:
-------------------
>>> a=0o27
>>> print(a,type(a))-------------23 <class 'int'>
>>> oct(a)-----------------------'0o27'
>>> a=0O123
>>> print(a,type(a))------------83 <class 'int'>
>>> oct(83)-----------------'0o123'
>>> a=0o148-------------Syntax Error: invalid digit '8' in octal literal
--------------------------------------------------------------------------------------------------------------------------------
4. Hexa Decimal Number System
=>This Number System Contains Digits: 0 1 2 3 4 5 6 7 8 9
A(10) B(11) C(12) D(13) E(14) F(15) ------Total Digits =16 Base : 16
=>All Base 16 Literals are called Hexa Decimal Data.
=>To Store Hexa Decimal Data in python environment, The Hexa Decimal Data Must be preceded
by a letter 'x' or 'X'
=>Syntax: varname=0x Hexa Decimal data (OR) varname=0X Hexa Decimal data
=>When we store the Hexa Decimal data in python environment, python Execution Environment
converts automatically into decimal number System data.

Examples:
>>> a=0xAC >>> print(a,type(a))->172 <class 'int'> >>> hex(172)->'0xac'
>>> a=0xBEE >>> print(a,type(a))->3054 <class 'int'>
>>> hex(3054)->'0xbee' >>> a=0XFacE >>> print(a,type(a))->64206 <class 'int'>
>>> a=0xBEER->SyntaxError: invalid hexadecimal literal
----------------------------------------------------------------------------------------------------------------
2. float
Properties:
=>'float' is one of the pre-defined class and treated as Fundamental data Type.
=>The purpose of float data type is that " To store Real Constant Values OR Floating Point
Values (Numbers with Decimal Places)".
3
=>Example: Percentage of Marks, Taxable income for Financial year 22-23..etc

=>float data type can store the data which belongs to Scientific Notation.
=>The Advantage of Scientific Notation is that " It Takes Less Memory Space for Extremely
Large Floating Point Values."
=>float data type does not support to store directly the values of Binary, Octal and Hexa Decimal
Number Systems. But it allows to store only Decimal Number System Values (Default)
Examples:
>>> a=12.34 >>> print(a,type(a))->12.34 <class 'float'>
>>> a=10 >>> b=2.3 >>> c=a+b >>> print(a,type(a))->10 <class 'int'>
>>> print(b,type(b))->2.3 <class 'float'> >>> print(c,type(c))->12.3 <class 'float'>
-------------------------------------------------------------------------------
>>> a=2e3 >>> print(a,type(a))->2000.0 <class 'float'>
>>> a=10e-2 >>> print(a,type(a))->0.1 <class 'float'>
>>> a=0.000000000000000000000000000000000000000000000000000001
>>> print(a,type(a))->1e-54 <class 'float'>
------------------------------------------------------------------------------
>>> a=0b1010.0b1010->SyntaxError: invalid decimal literal
>>> a=0b1010.34->SyntaxError: invalid syntax
>>> a=0xACC.0b1010->SyntaxError: invalid decimal literal
>>> a=0o23.0o45->SyntaxError: invalid decimal literal
-----------------------------------------------------------
3. bool
Properties
=>'bool' is one of the pre-defined class and treated as Fundamental Data Type.
=>The purpose of bool data type is that "To Store True and False Values".
=>In Python Prog, True and False are of the Keywords and They are the values for bool data type.
=>Internally, the value of True is 1 and the value of False is 0
Examples:
>>> a=True >>> print(a,type(a))->True <class 'bool'>
>>> b=False >>> print(b,type(b))->False <class 'bool'>
>>> a=true->NameError: name 'true' is not defined. Did you mean: 'True'?
>>> b=false->NameError: name 'false' is not defined. Did you mean: 'False'?
----------------------------------------------------------------------------------------------------------------
>>> a=True >>> print(a,type(a))->True <class 'bool'>
>>> b=False >>> print(b,type(b))->False <class 'bool'>
>>> print(a+b)->1 >>> print(False+False)->0 >>> print(False-True)->1
>>> print(True+True+False)->2 >>> print(2*True-4+False)->2
>>> print(0b1010+True+1)->12 >>> print(0b1111*False+2*True)->2
>>> print(0b100*2+3*True)->11
--------------------------------------------------------------------------------------------------------
>>> print(True>False)->True >>> print(True>1)->False
>>> print(True>=0b0000001)->True >>> print(False>=0.0)->True
>>> print(True*False>True)->False
-----------------------------------------------------------------------------------------------------------
4. complex
=>Properties
=>'complex' is one of the pre-defined class and treated as Fundamental Data Type.
=>The purpose of complex data type is that " To Store and Process Complex Data".
=>The General Notation of Complex Data Type is shown below.
a+bj or a-bj
=>here 'a' is called Real Part, 'b' is called Imaginary Part &'j' represents sqrt(-1)
4
=>Internally, The real and imaginary parts are by default belongs to float.
=>To Extract or get Real Part from Complex object, we use a pre-defined attribute called "real"
Syntax:- Complexobj.real
=>To Extract or get Imaginary Part from Complex object, we use a pre-defined attribute called "imag"
Syntax:- Complexobj.imag
Examples:
>>> a=2+3j >>> print(a,type(a))->(2+3j) <class 'complex'>
>>> b=4-5j >>> print(b,type(b))->(4-5j) <class 'complex'>
>>> c=-2-4j >>> print(c,type(c))->(-2-4j) <class 'complex'>
-----------------------------------------------
>>> a=1.4+3.4j >>> print(a,type(a))->(1.4+3.4j) <class 'complex'>
>>> b=-3.5-5.6j >>> print(b,type(b))->(-3.5-5.6j) <class 'complex'>
>>> c=10+2.3j >>> print(c,type(c))->(10+2.3j) <class 'complex'>
-----------------------------------------
>>> a=0+2j >>> print(a,type(a))->2j <class 'complex'>
>>> b=9.5j >>> print(b,type(b))->9.5j <class 'complex'>
----------------------------------------------------------------
>>> a=10.4+3j >>> print(a,type(a))->(10.4+3j) <class 'complex'>
>>> a.real->10.4 >>> a.imag->3.0
>>> a=9.5j >>> print(a,type(a))->9.5j <class 'complex'>
>>> a.real->0.0 >>> a.imag->9.5
>>> a.imagiary->AttributeError: 'complex' object has no attribute 'imaginary'
----------------------------------------------
>>> a=-3.4-4.5j >>> print(a,type(a))->(-3.4-4.5j) <class 'complex'>
>>> a.real-> -3.4 >>> a.imag-> -4.5
--------------------------------------------------------------------------------------------------------
>>> (12+4j).real->12.0 >>> (12+4j).imag-> 4.0 >>> (-0-2.3j).real-> 0.0
>>> (-0-2.3j).imag-> 2.3 >>> (0b1111+0b1010j).real->SyntaxError: invalid binary literal
>>> (0b1111+0b1010j).imag-> SyntaxError: invalid binary literal
==============================X==========================================
II. Sequence Category Data Types
=>The purpose of Sequence Category Data Types is that " To store Sequence of Values ".
=>We have 4 data types in Sequence Category. They are
1. str 2. bytes 3. bytearray 4. range
1. str (Part-1)
=>"str" is one of the pre-defined class and treated as Sequence Data Type.
=>The purpose of str data type is that " To store Text Data or Numeric Data or Alpha-numeric
Data and special symbols enclosed within Single or Double Quotes or Tripple Single or
Tripple Double Quotes."
=>Def. of str (String):
=>A String is sequence or Collection of Characters or Numbers or Alpha-numeric Data and special
symbols enclosed within Single or Double Quotes or Tripple Single or Tripple Double Quotes.
Types of str data
=>In Python Programming, we have 2 types of str data. They are
1. Single Line String Data 2. Multi Line String Data
1. Single Line String Data
=>Syntax: "String Data " (OR) ' String data '
=>Single Line string data always enclosed within Double or Single Quotes.
=>Double or Single Quotes are not useful for organizing Multi Line String Data.
2. Multi Line String Data
=>Syntax: """ String Line 1
5
String Line 2
------------------
String Line n " " "
(OR)
''' String Line 1
String Line 2
------------------
String Line n ' ' '
=>With Triple Double Quotes or Triple Single Quotes we can organize Multi Line String
data and also we can organize Single Line String data.
Examples:
>>> s1="Guido Van Rossum" >>> print(s1,type(s1))->Guido Van Rossum <class 'str'>
>>> s2="123456" >>> print(s2,type(s2))->123456 <class 'str'>
>>> s2="Python3.10.6" >>> print(s2,type(s2))->Python3.10.6 <class 'str'>
>>> s3='Travis Oliphant' >>> print(s3,type(s3))->Travis Oliphant <class 'str'>
>>> s4='1234python%$' >>> print(s4,type(s4))->1234python%$ <class 'str'>
>>> s5='A' >>> print(s5,type(s5))->A <class 'str'>
>>> s6='6' >>> print(s6,type(s6))->6 <class 'str'>
>>> s7='$%^&@' >>> print(s7,type(s7))->$%^&@ <class 'str'>
----------------------------------
>>> s1="Python Programming" >>> print(s1,type(s1))->Python Programming <class 'str'>
>>> s2='Python Programming' >>> print(s2,type(s2))->Python Programming <class 'str'>
------------------------------------------------------
>>> addr1="Guido van Rossum->SyntaxError: unterminated string literal (detected at line 1)

>>> addr1='Guido van Rossum->SyntaxError: unterminated string literal (detected at line 1)


-----------------------------------------------
>>> addr1="""Guido Van Rossum
... FNO:3-4, Red Sea Side
... Python Software Foundation
... Nether Lands
... Pin-57 """
>>> print(addr1, type(addr1))
Guido Van Rossum
FNO:3-4, Red Sea Side
Python Software Foundation
Nether Lands
Pin-57 <class 'str'>
---------------------------------
>>> addr2='''Travis Oliphant... Numpy Organization... FNO-34-56 Nether lands... PIN-45 '''
>>> print(addr2,type(addr2))
Travis Oliphant Numpy Organization FNO-34-56 Nether landsPIN-45 <class 'str'>
----------------------------------------------------------------------------------------
>>> s1="""Python Programming""">>> print(s1,type(s1))->Python Programming <class 'str'>
>>> s1='''Python Programming'''>>> print(s1,type(s1))->Python Programming <class 'str'>
>>> s2="""K""" >>> print(s2,type(s2))->K <class 'str'>
>>> s2='''K''' >>> print(s2,type(s2))->K <class 'str'>
-------------------------------------------------------------------------------------
Operations on str data (Part-1)
=>On str data, we can perform 2 types of Operations. They are
1. Indexing Operation 2. Slicing Operations
1. Indexing Operation
6
=>The Process of Obtaining Single Character from given str object by passing valid Index is
called Indexing.
=>Syntax: strobj [ Index ]
=>Here strobj is an object of <class, 'str'>
=>Index can be either +Ve Indexing or -Ve Indexing
=>If we enter valid Index value then we get Corresponding Character from strobj.
=>If we enter invalid Index value then we get IndexError.
Examples:
>>> s="PYTHON"
>>> print(s[3])->H >>> print(s[-2])->O >>> print(s[4])->O >>> print(s[-6])->P
>>> print(s[0])->P >>> print(s[-5])->Y >>> print(s[-1])->N >>> print(s[3])->H
>>> print(s[-3])->H >>> print(s[-13])->IndexError: string index out of range
------------------------------------------------------
>>> s="PYTHON" >>> print(s,type(s))->PYTHON <class 'str'> >>> len(s)->6
>>> s="Python Prog" >>> len(s)->11 >>> print(s[34])->IndexError: string index out of range
-----------------------------------------------------------------------------------------------------------------------------------
2. Slicing Operations
=>The Process of obtaining Range of Characters or Sub String / Str object is called Slicing.
=>Slicing Operation can be performed by using 5 Syntaxes. -
Syntax-1: Strobj[ Begin Index : End Index]
This Syntax obtains range of characters from BeginIndex to EndIndex-1 provided Begin Index<End
Index Otherwise we never get any output (‘ ')
Examples
>>> s="PYTHON" >>> print(s,type(s))->PYTHON <class 'str'>
>>> print( s[0:4] )->PYTH >>> print( s[4:0] )->Empty >>> s[4:0]->' '
>>> print( s[2:5] )->THO >>> print( s[0:6] )->PYTHON >>> print( s )->PYTHON
>>> print(s[-6:-3])->PYT >>> print(s[-4:-1])->THO >>> print(s[-1:-6])-> Empty
>>> print(s[2:6])->THON >>> print(s[2:-2])-> TH >>> print(s[1:-1])->YTHO
>>> print(s[-1:-6])-> empty
>>> s[-1:-6]->' ' >>> s[2:-1]->'THO' >>> s[-6:4]->'PYTH' >>> s[2:-4]->' '
-----------------------------------------------------------------------------
Syntax-2: StrObj[BeginIndex : ]

=>In This Syntax We specified Begin Index and Did't not specify End Index.
=>If we don't Specify End Index then PVM always takes End Character Index as End Index OR
len(strobj)-1
Examples:
>>> s="PYTHON" >>> print(s,type(s))>PYTHON <class 'str'>
>>> s[2:]->'THON' >>> s[1: ]->'YTHON' >>> s[0: ]->'PYTHON'
>>> s[-4: ]->'THON' >>> s[-6: ]->'PYTHON' >>> s[-3: ]->'HON'
--------------------------------------------------------------------------------------------------------------------------
Syntax-3: StrObj[ : EndIndex ]
=>In This Syntax We specified End Index and Did't not specify Begin Index.
=>If we don't Specify Begin Index then PVM always takes First Character Index as Begin
Index.
Examples:
>>> s="PYTHON" >>> print(s,type(s))->PYTHON <class 'str'>
>>> s[:4]->'PYTH' >>> s[:3]->'PYT' >>> s[:6]->'PYTHON'
>>> s[:-4]->'PY' >>> s[:-5]->'P' >>> s[:-3]->'PYT'
>>> s[:0]->' ' empty >>> s[:-6]->' ' empty
-----------------------------------------------------------------------------------------------------------
Syntax-4: StrObj[ : ]
7
=>In This Syntax We Did't not specify Begin Index and End Index.
=>If we don't Specify Begin Index then PVM always takes First Character Index as Begin
Index and If we don't Specify End Index then PVM always takes Last Character Index as End Index
(OR) len(strobj)-1 as End Index.
Examples:
>>> s="PYTHON" >>> s[:]->'PYTHON' >>> s[0:]->'PYTHON'
>>> s[:-6]->' ' Empty >>> s[:6]-> 'PYTHON' >>> s[-6:]->'PYTHON'
>>> s[:-5]->'P' >>> s[:-4]->'PY' >>> s[-3:]->'HON'
>>> s[-6:6]->'PYTHON'
--------------------------------------------------------------------------------------------------------------------------
Most IMP:
>>> s="PYTHON" >>> s[-13:-6]->' ' >>> s[-13:6]->'PYTHON'
>>> s[0:123]->'PYTHON' >>> s[-123:345]->'PYTHON'
NOTE:- All the Above Syntaxes are obtaining Range of Characters In Forward Direction.
--------------------------------------------------------------------------------------------------------------------------
Syntax-5 : Strobj[BeginIndex :End Index : Step]

Rules:
1) Here Begin Index, End Index and Step can either +VE INDEX and -VE INDEX
2) If the value of STEP is +VE then PVM takes the Range of Characters from Begin Index to
End Index-1 in Forward Direction provided Begin Index<End Index otherwise we get empty
String(' ' )
3) if the value of STEP is -VE then PVM Takes Range of Characters from BeginIndex to End
Index+1 in Backward Direction provided Begin Index > End Index

4) When we are retrieving the data in forward Direction if the EndIndex Value is 0 then we never get
any result / output.
5) When we are retrieving the data in backward Direction if the EndIndex Value is -1 then we never
get any result / output.

Examples:
>>> s="PYTHON" >>> s[0:6:1]->'PYTHON' >>> s[0:6:2]->'PTO'
>>> s[2:4:1]->'TH' >>> s[-6: :1]->'PYTHON' >>> s[:6:1]->'PYTHON'
>>> s[:-2:2]->'PT' >>> s[6:2:2]->' ' >>> s[0:6:2]->'PTO'
>>> s[0:6:-2]-> ' ' >>> s[5:0:-1]->'NOHTY' >>> s[5: :-1]->'NOHTYP'
>>> s[-1:-7:-1]->’NOHTYP'>>> s[-1:-7:-2]->'NHY' >>> s[::-1]->'NOHTYP'
>>> s="MADAM" >>> s==s[::-1]>True
>>> s="LIRIL" >>> s[::]==s[::-1]->True
>>> "MALAYALAM"=="MALAYALAM"[::-1] ->True
>>> "RACECAR"[::]=="RACECAR"[::][::-1] ->True
>>> "PYTHON"=="PYTHON"[::-1]->False
>>> print("KVR"[::3])->K >>> "KVR"[::3]=="KVR"[::-1][-1]->True
>>> s="PYTHON PROG" >>> s[::-1]->'GORP NOHTYP'
>>> s="121" >>> s==s[::-1]->True
>>> "8558"=="8558"[::-1]->True
>>> s[2:-1:1]->'THO' >>> s[2:0:1]->' ' (Rule-5) >>> s[1:0:2]->' '
>>> s[-6:-1:-1]-> ' ' (Rule-6) >>> s[-3:-1:-2]->' '
>>> s[-6:6:-2]->' ' >>> s[2:-1:-2]->' '
>>> s[1:-1:3]->'YO' >>> s[1:-1:-3]>' ' >>> s[1::-3]->'Y'
>>> s[-2::-2]->’OTP' >>> s[-2::-2][::-1]->'PTO'
------------------------------------------------------------------------------------------------------------------------------
Type Casting Techniques in Python
8
=>The Process of Converting One Type of Possible Value into Another Type of Value is called
Type Casting.
=>Fundamentally, we have 5 types of Type Casting Techniques. They are

1. int() 2. float() 3. bool() 4. complex() 5. str()


---------------------------------------------------------------------------------------------------------------------
1. int()
=>int() is used converting any Possible Type of Value into int type Value

=>Syntax:- varname=int( float / bool / complex / str)

Examples: float into int--->Possible


>>> a=12.34 >>> print(a,type(a))->12.34 <class 'float'>
>>> b=int(a) >>> print(b,type(b))->12 <class 'int'>
>>> a=0.99 >>> print(a,type(a))->0.99 <class 'float'>
>>> b=int(a) >>> print(b,type(b))->0 <class 'int'>
-----------------------------------------
Examples: bool into int--->Possible
>>> a=True >>> print(a,type(a))->True <class 'bool'>
>>> b=int(a) >>> print(b,type(b))-> 1 <class 'int'>
>>> a=False >>> print(a,type(a))->False <class 'bool'>
>>> b=int(a) >>> print(b,type(b))-> 0 <class 'int'>
------------------------------------------------------------------------------------------------
Examples: complex into int--->Not Possible
>>> a=2+3j >>> print(a,type(a))->(2+3j) <class 'complex'> >>> b=int(a)->TypeError: int()
argument must be a string, a bytes-like object or a real number, not 'complex'
------------------------------------------------------------------------------------------------
Examples:
Case-1: Str int->int->Possible
>>> a="123" # str int >>> print(a,type(a))->123 <class 'str'>
>>> b=int(a) >>> print(b, type(b))->123 <class 'int'>

Case-2: Str float->int->Not Possible


>>> a="12.34" # Str float >>> print(a,type(a))->12.34 <class 'str'>
>>> b=int(a)->ValueError: invalid literal for int() with base 10: '12.34'
-----------------------------------------------------------------------------------
Case-3: Str bool-> int->Not Possible
>>> a="True" # str bool
>>> print(a,type(a))-----------------True <class 'str'>
>>> b=int(a)------------------------ValueError: invalid literal for int() with base 10: 'True'
-----------------------------------------------------------------------------------
Case-4: str complex--->int---->Not Possible
>>> a="2+3j"
>>> print(a,type(a))-------------------------------2+3j <class 'str'>
>>> b=int(a)-----------------------ValueError: invalid literal for int() with base 10: '2+3j'
-----------------------------------------------------------------------------------
Case-5 :Pure Str--->int--->Not Possible
>>> a="KVR"
>>> print(a,type(a))-----------------KVR <class 'str'>
>>> b=int(a)-------------------------ValueError: invalid literal for int() with base 10: 'KVR'
-----------------------------------------------------------------------------------
2. float()
9
=>float() is used converting any Possible Type of Value into float type Value
=>Syntax:- varname=float( int / bool / complex / str)
--------------------------------------------------------------------------------------------------------------
Example: int----->float--->Possible
--------------------------------------------------------------------------------------------------------------
>>> a=10
>>> print(a,type(a))---------------10 <class 'int'>
>>> b=float(a)
>>> print(b,type(b))---------------10.0 <class 'float'>
--------------------------------------------------------------------------------------------------------------
Example: bool----->float--->Possible
--------------------------------------------------------------------------------------------------------------
>>> a=True
>>> print(a,type(a))--------------------True <class 'bool'>
>>> b=float(a)
>>> print(b,type(b))---------------------1.0 <class 'float'>
>>> a=False
>>> print(a,type(a))---------------------False <class 'bool'>
>>> b=float(a)
>>> print(b,type(b))-------------------0.0 <class 'float'>
--------------------------------------------------------------------------------------------------------------
Example: complex----->float--->Not Possible
--------------------------------------------------------------------------------------------------------------
>>> a=2.3+4.5j
>>> print(a,type(a))------------------(2.3+4.5j) <class 'complex'>
>>> b=float(a)-------------TypeError: float() argument must be a string or a real number, not 'complex'
>>> a=2.3+4.5j
>>> print(a,type(a))--------------(2.3+4.5j) <class 'complex'>
>>> b=float(a.real)
>>> print(b,type(b))--------------2.3 <class 'float'>
>>> b=float(a.imag)
>>> print(b,type(b))-----------4.5 <class 'float'>
--------------------------------------------------------------------------------------------------------------
Example:
--------------------------------------------------------------------------------------------------------------
Case-1 str int----->float -->Possible
----------------------------------------------------
>>> a="12"
>>> print(a,type(a))------------12 <class 'str'>
>>> b=float(a)
>>> print(b, type(b))----------12.0 <class 'float'>
----------------------------------------------------
Case-2 str float----->float -->Possible
----------------------------------------------------
>>> a="12.34"
>>> print(a,type(a))-----------------12.34 <class 'str'>
>>> b=float(a)
>>> print(b, type(b))-----------------12.34 <class 'float'>
-----------------------------------------------------------------------------
Case-3 str bool----->float -->Not Possible
--------------------------------------------------------------------------------
>>> a="True"

10
>>> print(a,type(a))-----------------True <class 'str'>
>>> b=float(a)------------ValueError: could not convert string to float: 'True'
-------------------------------------------------------------------------------------
Case-4 str complex----->float -->Not Possible
--------------------------------------------------------------------------------
>>> a="2+3.5j"
>>> print(a,type(a))-----------------------------------2+3.5j <class 'str'>
>>> b=float(a)----------------------------------------ValueError: could not convert string to float: '2+3.5j'
---------------------------------------------------------------------------------------
Case-5 Pure str ----->float -->Not Possible
--------------------------------------------------------------------------------
>>> a="Python.kvr"
>>> print(a,type(a))---------------------Python.kvr <class 'str'>
>>> b=float(a)------------------ValueError: could not convert string to float: 'Python.kvr'
--------------------------------------------------------------------------------------------------------------------------
===========================================
3. bool()
===========================================
=>bool() is used converting any Possible Type of Value into bool type Value

=>Syntax:- varname=bool( int / float / complex / str)


=>ALL NON-ZERO VALUES ARE TREATED AS TRUE
=>ALL ZERO VALUES ARE TREATED AS FALSE
------------------------------------------------------------------------------------------------------------------
Example: int----->bool---->Possible
------------------------------------------------------------------------------------------------------------------
>>> a=10
>>> print(a,type(a))------------------------------10 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))-----------------------------True <class 'bool'>
>>> a=-123
>>> print(a,type(a))------------------------------123 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))-----------------------------True <class 'bool'>
>>> a=0
>>> print(a,type(a))-----------------------------0 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))----------------------------False <class 'bool'>
------------------------------------------------------------------------------------------------------------------
Example: float----->bool---->Possible
------------------------------------------------------------------------------------------------------------------
>>> a=12.34
>>> print(a,type(a))
12.34 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a=0.0
>>> print(a,type(a))
0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))
11
False <class 'bool'>
>>>
>>>
>>> a=0.000000000000000000000000000000000000000000000000000000001
>>> print(a,type(a))
1e-57 <class 'float'>
>>> print(b,type(b))
False <class 'bool'>
>>>
>>> a=0.000000000000000000000000000000000000000000000000000000001
>>> print(a,type(a))
1e-57 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a=0.00000000000000000000000000000000000000000000000000000
>>> print(a,type(a))
0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))
False <class 'bool'>
---------------------------------------------------------------------------------------------------
Example: complex----->bool---->Possible
------------------------------------------------------------------------------------------------------------------
>>> a=2+3j
>>> print(a,type(a))
(2+3j) <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a=0+0j
>>> print(a,type(a))
0j <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))
False <class 'bool'>
------------------------------------------------------------------------------------
Example: Str int,float,complex,bool and pure str are possible to convert into bool type
Here bool type True provided len(strobj) is >0
Here bool type Frue provided len(strobj) is ==0
------------------------------------------------------------------------------------------------------------------
>>> a="123"
>>> print(a,type(a))
123 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a="0"
>>> len(a)
1
>>> print(a,type(a))
0 <class 'str'>

12
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>

>>> a="False"
>>> print(a,type(a))
False <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a="12.34"
>>> print(a,type(a))
12.34 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a=" "
>>> print(a,type(a))
<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a=""
>>> len(a)
0
>>> print(a,type(a))
<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
False <class 'bool'>

>>> a="KVR"
>>> print(a,type(a))
KVR <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>>
=====================================
complex ()
=====================================
=>complex() is used converting any Possible Type of Value into complex type Value

=>Syntax:- varname=complex( int / float / bool / str)


------------------------------------------------------------------------------------------------------
Examples: int------>complex----->Possible
------------------------------------------------------------------------------------------------------
>>> a=12
>>> print(a,type(a))--------------------------12 <class 'int'>
>>> b=complex(a)
>>> print(b,type(b))-----------------------(12+0j) <class 'complex'>
------------------------------------------------------------------------------------------------------
13
Examples: float------>complex----->Possible
------------------------------------------------------------------------------------------------------
>>> a=2.3
>>> print(a,type(a))----------------2.3 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))-----------------(2.3+0j) <class 'complex'>
------------------------------------------------------------------------------------------------------
Examples: bool------>complex----->Possible
------------------------------------------------------------------------------------------------------
>>> a=True
>>> print(a,type(a))----------------------True <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))---------------------(1+0j) <class 'complex'>
>>> a=False
>>> print(a,type(a))---------------------False <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))---------------------0j <class 'complex'>
------------------------------------------------------------------------------------------------------
Examples:
------------------------------------------------------------------------------------------------------
>>> a="12" # str int-----complex--Possible
>>> print(a,type(a))----------------------12 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))--------------------(12+0j) <class 'complex'>
------------------------------------------------------------
>>> a="12.45" #str float------complex---->Possible
>>> print(a,type(a))-----------------12.45 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))----------------(12.45+0j) <class 'complex'>
------------------------------------------------------------
>>> a="True" # str bool----->complex----Not Possible
>>> print(a,type(a))----------------True <class 'str'>
>>> b=complex(a)-------------ValueError: complex() arg is a malformed string
-------------------------------------------------------------------------------------------
>>> a="KVR-PYTHON" # Pure Str-------->Complex--Not Possible
>>> print(a,type(a))-------------------------KVR-PYTHON <class 'str'>
>>> b=complex(a)--------------ValueError: complex() arg is a malformed string
--------------------------------------------------x-------------------------------------------------------------------------
5. str()
=>str() is used converting all types of values into str type value.
=>Syntax:- varname=str (int / float / bool / complex)
Examples:
>>> a=123
>>> print(a,type(a))--------------------------123 <class 'int'>
>>> b=str(a)
>>> print(b,type(b))--------------------------123 <class 'str'>
>>> b---------------------------------------- '123'
>>> a=12.34
>>> print(a,type(a))-----------------------12.34 <class 'float'>
>>> b=str(a)
>>> print(b,type(b))----------------------12.34 <class 'str'>
>>> b----------------------------------------'12.34'
14
>>> a=True
>>> print(a,type(a))--------------------True <class 'bool'>
>>> b=str(a)
>>> print(b,type(b))-------------------True <class 'str'>
>>> b---------------------------------------'True'
>>> a=2+3.5j
>>> print(a,type(a))---------------------(2+3.5j) <class 'complex'>
>>> b=str(a)
>>> print(b,type(b))--------------------(2+3.5j) <class 'str'>
>>> b---------------------------------------'(2+3.5j)'
=====================================X================================
2. bytes
Properties:
=>"bytes" if one of the pre-defined class and treated as Sequence Data Type/Cipher Text
=>The Internal Implementation of bytes data type is that "End-to-End Encryption (OR) Cipher
Text (OR) Encrypted Data" of Normal Text.
=>The bytes data stores the data in the range of 0 to 255 (256-1 only)
=>bytes data type does not contain any symbolic notation but we can convert other type of
values into bytes type values by using bytes().
=>Syntax: varname=bytes(object)
=>An object of bytes belongs to Immutable bcoz bytes object does not support item
Assignment.
=>An object of bytes data type supports Both Indexing and Slicing Operations.
=>An object of bytes maintains Insertion Order (i.e Which ever order we insert the data in the
same order Value will display)
Examples:
>>> l1=[10,20,30,40,256]
>>> print(l1,type(l1))------------------------[10, 20, 30, 40, 256] <class 'list'>
>>> b=bytes(l1)-------------------ValueError: bytes must be in range(0, 256)
>>> l1=[10,0,-20,30,40,255]
>>> print(l1,type(l1))-----------------[10, 0, -20, 30, 40, 255] <class 'list'>
>>> b=bytes(l1)--------------------ValueError: bytes must be in range(0, 256)

>>> l1=[10,0,30,40,255]
>>> print(l1,type(l1))----------------------[10, 0, 30, 40, 255] <class 'list'>
>>> b=bytes(l1)
>>> print(b, type(b),id(b))-------------b'\n\x00\x1e(\xff' <class 'bytes'> 2043775384912
>>> b[-1]--------------------------255
>>> b[0]----------------------------10
>>> b[0]=123-----------------TypeError: 'bytes' object does not support item assignment
---------------------------------------------------------
>>> l1=[10,0,30,40,255]
>>> print(l1,type(l1))----------------------[10, 0, 30, 40, 255] <class 'list'>
>>> b=bytes(l1)
>>> print(b, type(b),id(b))-----------b'\n\x00\x1e(\xff' <class 'bytes'> 2043775382752
>>> for kvr in b:
... print(kvr)
10 0 30 40 255
>>> t1=(10,20,30,10,255,45)
>>> print(t1,type(t1))---------------------(10, 20, 30, 10, 255, 45) <class 'tuple'>

15
>>> b=bytes(t1)
>>> print(b,type(b),id(b))-------------b'\n\x14\x1e\n\xff-' <class 'bytes'> 2043775382800
>>> for v in b:
... print(v)
10 20 30 10 255 45
>>> b[0:4]--------------------b'\n\x14\x1e\n'
>>> for v in b[0:4]:
... print(v)
10 20 30 10
>>> for v in b[::-1]:
... print(v)
45 255 10 30 20 10
=================================X=================================
Mutable and Immutable
=>A Mutable object is one, whose content can be changed at Same Memory Address.
=>Examples: list, bytearray,set,dict
=>An immutable object is one, which will satisfy the following Properties
a) The value immutable object can't be changed at Same Memory Address (OR) In
otherwords, Value of Immutable object can be changed and place the modified Value in New
Memory Address by eliminating Old Memory Address by Garbage Collector.
b) Immutable objects does not support Item Assignment.
Examples: int, float, bool, complex, str, bytes, range, tuple, set,frozenset, etc
===================================x==================================
3. bytearray
Properties:
=>"bytearray" if one of the pre-defined class and treated as Sequence Data Type.
=>The Internal Implementation of bytearray data type is that "End-to-End Encryption (OR)
Cipher Text (OR) Encrypted Data" of Normal Text.
=>The bytearray data stores the data in the range of 0 to 255 (256-1 only)
=>bytearray data type does not contains any symbolic notation but we can convert other type of
values into bytearray type values by using bytearray().
=>Syntax: varname=bytearray(object)
=>An object of bytearray belongs to Mutable bcoz bytearray object supports item
assignment
=>An object of bytearray data type supports Both Indexing and Slicing Operations.
=>An object of bytearray maintains Insertion Order (i.e Which ever order we insert the data in
the same order Value will display)
=>NOTE:- The Functionality of bytearray is exactly similar to bytes but an object of bytes
belongs to immutable where as an object of bytearray is mutable.
=====================================================================
Examples:
>>> l1=[10,20,30,40,0,256]
>>> print(l1,type(l1))------------------------------[10, 20, 30, 40, 0, 256] <class 'list'>
>>> b=bytearray(l1)--------------------ValueError: byte must be in range(0, 256)
>>> l1=[10,-20,30,40,0,255]
>>> print(l1,type(l1))------------------[10, -20, 30, 40, 0, 255] <class 'list'>
>>> b=bytearray(l1)----------------------ValueError: byte must be in range(0, 256)
--------------------------------------------------------
>>> l1=[10,20,30,40,0,255]
>>> print(l1,type(l1))-----------------[10, 20, 30, 40, 0, 255] <class 'list'>
>>> b=bytearray(l1)
>>> print(b,type(b),id(b))----bytearray(b'\n\x14\x1e(\x00\xff') <class 'bytearray'>
16
2376795361136
>>> for k in b:
... print(k)
10 20 30 40 0 255
>>> b[0]=120 # Item Assignment---Possible--Mutable
>>> for k in b:
... print(k)
120 20 30 40 0 255
>>> print(b,type(b),id(b))--bytearray(b'x\x14\x1e(\x00\xff') <class 'bytearray'> 2376795361136
>>> b[1]--------------------------20
>>> b[1:4]----------------------bytearray(b'\x14\x1e(')
>>> for k in b[1:4]:
... print(k)
20 30 40
>>> for k in b[::-1]:
... print(k)
255 0 40 30 20 120
================================X====================================
4. range
Properties
=>"range" is one of the pre-defined class and treated as Sequence Data Type
=>The purpose of range data type is that "To store or generate Sequence of Numerical
Integer Values by maintaining Equal Interval of Value."
=>On the object of range data type, we can perform Both Indexing and Slicing Operations
=>An object of range belongs to immutable.
=>An object of range maintains Insertion Order.
=>To store or generate Sequence of Numerical Integer Values by maintaining Equal Interval
of Value, range data type provides 3 Syntaxes. They are.
------------------------------------------------------------------------------------------
=>Syntax-1: varname=range(Value)
=>This Syntax generates Range of Values from 0 to Value-1
Examples:
-------------------
>>> r=range(10)
>>> print(r,type(r))----------------range(0, 10) <class 'range'>
>>> for v in r:
... print(v)
0 1 2 3 4 5 6 7 8 9
>>> for k in range(6):
... print(k)
0 1 2 3 4 5
---------------------------------------------------------------------------------------------
=>Syntax-2: varname=range(Begin , End )

=>This generates Range of Values from Begin to End-1


Examples:
-------------------
>>> r=range(10,16)
>>> print(r,type(r))------------range(10, 16) <class 'range'>
>>> for v in r:
... print(v)
10 11 12 13 14 15
17
>>> for k in range(6):
... print(k)
0 1 2 3 4 5
=>NOTE: In the above Two Syntaxes, the default STEP is 1
---------------------------------------------------------------------------------------------
=>Syntax-3: varname=range(Begin, End, Step)
=>This generates Range of Values from Begin to End-1 by maintaining Step as Equal Interval.
---------------------------------------------------------------------------------------------
Examples:
----------------------
>>> r=range(10,21,3)
>>> print(r,type(r))---------------------range(10, 21, 3) <class 'range'>
>>> for v in r:
... print(v)
10 13 16 19
>>> for v in range(2,21,2):
... print(v)
2 4 6 8 10 12 14 16 18 20
>>> for v in range(1,21,2):
... print(v)
1 3 5 7 9 11 13 15 17 19
--------------------------------------------------------------------------------------------------------------
Programming Examples:
--------------------------------------------------------------------------------------------------------------
Q1) 0 1 2 3 4 5 6 7 8 9 -------range(10)

>>> for v in range(10):


... print(v)
0 1 2 3 4 5 6 7 8 9
-----------------------------------------------------------------------------
Q2) 10 11 12 13 14 15---range(10,16)
>>> for v in range(10,16):
... print(v)
10 11 12 13 14 15
----------------------------------------------------------------------------
Q3) 300 301 302 303 304 305---range(300,306)
>>> for v in range(300,306):
... print(v)
300 301 302 303 304 305
----------------------------------------------------------------------------
Q4) 10 9 8 7 6 5 4 3 2 1-----range(10,0,-1)
----------------------------------------------------------------------------
>>> for v in range(10,0,-1):
... print(v)
10 9 8 7 6 5 4 3 2 1
----------------------------------------------------------------------------
Q5) -10 -11 -12 -13 -14 -15------range(-10,-16,-1)
>>> for v in range(-10,-16,-1):
... print(v)
-10 -11 -12 -13 -14 -15
----------------------------------------------------------------------------

18
Q6) 100 110 120 130 140 150--range(100,151,10)
>>> for k in range(100,151,10):
... print(k)
100 110 120 130 140 150
----------------------------------------------------------------------------------------------------
Q7) 1000 900 800 700 600 500-----range(1000,499,-100)

>>> for v in range(1000,499,-100):


... print(v)
1000 900 800 700 600 500
----------------------------------------------------------------------------------------------------
Q8) -5 -4 -3 - 2 -1 0 1 2 3 4 5----range(-5,6)

>>> for v in range(-5,6,1):


... print(v)
-5 -4 -3 -2 -1 0 1 2 3 4 5
>>> for v in range(-5,6):
... print(v)
-5 -4 -3 -2 -1 0 1 2 3 4 5
----------------------------------------------------------------------------------------------------
>>> r=range(500,601,50)
>>> r[0]
500
>>> r[1]
550
>>> r[-1]
600
>>> r[2]
600
>>> r=range(500,601,10)
>>> r[-1]
600
>>> for v in r:
... print(v)
500 510 520 530 540 550 560 570 580 590 600
>>> for v in r[5:]:
... print(v)
550 560 570 580 590 600
>>> for v in r[5:][::-1]:
... print(v)
600 590 580 570 560 550
-------------------------------------------------------------------------------------
>>> r=range(500,601,10)
>>> print(r,type(r))
range(500, 601, 10) <class 'range'>
>>> r[0]
500
>>> r[1]
510
>>> r[2]
520
>>> r[1]=700-------------------TypeError: 'range' object does not support item assignment

19
-------------------------------------------------------------------------------------------------------------------------
>>> print(range(50,60)[5])------------------55
>>> for v in range(50,60)[5:7]:
... print(v)
55 56
>>> for v in range(50,60)[::-2]:
... print(v)
59 57 55 53 51
=============================X==============================================
==================================================================
List Category Data Types (Collections Data Types or Data Structures)
==================================================================
=>The purpose of List Category Data Types in python is that " To Store Multiple Values either of Same
Type or Different Type or Both the Types with Unique and Duplicate in single object."
=>We have two data type in List Category. They are
1. list ( Mutable) 2. tuple (Immutable)
--------------------------------------------------------------------------------------------------------------------
=========================================
list
=========================================
Index
---------
=>Purpose of list
=>Operations on list
1) Indexing 2) slicing
=>Pre-Defined Functions in list
1) append() 2) insert() 3) remove() 4) pop(index) 5) pop()Note: del operator
6) count() 7) index() 8) reverse() 9) sort() 10) extend()
11) copy()---- Shallow and Deep copy
=>Inner List / Nested List
=>Pre-defined Function in inner / nested list
===========================================================================
Properties of list
-------------------------------------------------------------------------------------------------------------------------------
=>'list' is one of the pre-defined class and treated as List data type.
=>The purpose of list data type is that "To Store Multiple Values either of Same Type or
Different Type or Both the Types with Unique and Duplicate in single object.
=>The Elements of list must written or Organized or stored within Square Brackets and the
elements separated by Comma.
=>An object of list maintains Insertion Order.
=>On the object of list, we can perform both Indexing and Slicing Operations.
=>An object of list belongs to Mutable bcoz it allows us to update the values of list at same
address.
=>We can convert any type of value into list type value by using list()
Syntax: listobj=list(object)
=>by using list data type, we can create two types of list objects. They are

1) empty list
2) non-empty list
---------------------
1) empty list
---------------------
20
Syntax: varname=[]
(OR)
varname=list()
=>An empty list is one, which does not contain any elements and whose length=0
-------------------------------------------------------------------------------------------------------------------------
2) non-empty list
-------------------------------------------------------------------------------------------------------------------------
Syntax: varname=[Val1,Val2...Val-n]
=>A non-empty list is one, which contains elements and whose length>0
-------------------------------------------------------------------------------------------------------------------------
Examples:
-------------------------------------
>>> l1=[10,20,30,10,40]
>>> print(l1,type(l1))------------------------------[10, 20, 30, 10, 40] <class 'list'>
>>> l1=[111,"Rossum",34.56,True,"Python"]
>>> print(l1,type(l1))-----------------------------[111, 'Rossum', 34.56, True, 'Python'] <class 'list'>
>>> l1[0]--------------------------------------------111
>>> l1[-1]-------------------------------------------'Python'
>>> l1[0:3]-----------------------------------------[111, 'Rossum', 34.56]
-------------------------------------------------------
>>> print(l1,type(l1))-------------------------[111, 'Rossum', 34.56, True, 'Python'] <class 'list'>
>>> print(l1,type(l1),id(l1))----[111, 'Rossum', 34.56, True, 'Python'] <class 'list'> 2902431303872
>>> l1[0]=222
>>> print(l1,type(l1),id(l1))---[222, 'Rossum', 34.56, True, 'Python'] <class 'list'> 2902431303872
----------------------------------------
>>> l1=[]
>>> print(l1,type(l1))------------------[] <class 'list'>
>>> len(l1)------------------------------0
>>> l2=list()
>>> print(l2type(l2))-------------------[] <class 'list'>
>>> len(l2)--------------------------------0
>>> l3=[10,"Rossum","PSF",3.4,True]
>>> print(l3,type(l3))--------------------[10, 'Rossum', 'PSF', 3.4, True] <class 'list'>
>>> len(l3)-----------------------------5
------------------------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))-----------------PYTHON <class 'str'>
>>> l1=list(s)
>>> print(l1,type(l1))----------------['P', 'Y', 'T', 'H', 'O', 'N'] <class 'list'>
--------------------------------
>>> l1=[10,20,30,40]
>>> b=bytes(l1)
>>> print(b,type(b))-----------------------b'\n\x14\x1e(' <class 'bytes'>
>>> l2=list(b)
>>> print(l2,type(l2))--------------------[10, 20, 30, 40] <class 'list'>
-------------------------------------------------------------------------------
>>> l1=[10,20,30,40]
>>> l1[2]-------------------------30
>>> l1[-2]-------------------------30
>>> l1[::2]-----------------------[10, 30]
>>> l1[::-1]-----------------------[40, 30, 20, 10]
>>> l1[::]-------------------------[10, 20, 30, 40]
21
===============================X==========================
Pre-Defined Functions in list
=>Along with the operations on list like Indexing and Slicing, we can perform many more
operations by using pre-defined function of list object.
=>The pre-defined functions of list are given bellow.
1) append():
=>Syntax: listobj.append(Value)
=>This Function is used for adding Value at the end of existing elements of list( known as
appending )
Examples:
>>> l1=[10,"Rossum"]
>>> print(l1,type(l1),id(l1))------------------------[10, 'Rossum'] <class 'list'> 2902435500480
>>> len(l1)--------------2
>>> l1.append(23.45)
>>> print(l1,type(l1),id(l1))----[10, 'Rossum', 23.45] <class 'list'> 2902435500480
>>> l1.append("KVR")
>>> print(l1,type(l1),id(l1))---[10, 'Rossum', 23.45, 'KVR'] <class 'list'> 2902435500480
>>> l1.append(True)
>>> l1.append(2+3.5j)
>>> print(l1,type(l1),id(l1))---[10, 'Rossum', 23.45, 'KVR', True, (2+3.5j)] <class 'list'>
2902435500480
>>> len(l1)----6
------------------------------------------------------
>>> l1=[]
>>> print(l1,len(l1), id(l1))------------------[] 0 2902435500544
>>> l1.append(10)
>>> l1.append("Raj")
>>> l1.append(10.34)
>>> l1.append("Hyd")
>>> print(l1,len(l1), id(l1))----------------[10, 'Raj', 10.34, 'Hyd'] 4 2902435500544
------------------------------------------------------------------------------------------------------------------------------
2) insert()
=>Syntax:- listobj.insert(Index, Value)
=>Here Index can be either +Ve or -Ve
=>Value can be any type.
=>This Function is used for Inserting the Specific Value at specified index.
Examples:
>>> l1=[10,20,30,"Python","DJango",34.56]
>>> print(l1,id(l1))--------------------[10, 20, 30, 'Python', 'DJango', 34.56] 2902431529344
>>> l1.insert(3,"Rossum")
>>> print(l1,id(l1))-----[10, 20, 30, 'Rossum', 'Python', 'DJango', 34.56] 2902431529344
>>> l1[-3]="PYTH"
>>> print(l1,id(l1))----[10, 20, 30, 'Rossum', 'PYTH', 'DJango', 34.56] 2902431529344
>>> l1.insert(1,234.99)
>>> print(l1,id(l1))----[10, 234.99, 20, 30, 'Rossum', 'PYTH', 'DJango', 34.56] 2902431529344
--------------------------------
>>> l1=list()
>>> print(l1,id(l1))---------------[] 2902435501056
>>> l1.insert(0,"KVR")
>>> print(l1,id(l1))---------------['KVR'] 2902435501056
>>> l1.insert(0,1111)
>>> print(l1,id(l1))----------------[1111, 'KVR'] 2902435501056
22
>>> l1.insert(2,"HYD")
>>> print(l1,id(l1))--------------[1111, 'KVR', 'HYD'] 2902435501056
-----------------------------
>>> l1=[10,20,30]
>>> print(l1,id(l1))
[10, 20, 30] 2902435496128
>>> l1.append("Python")
>>> print(l1,id(l1))
[10, 20, 30, 'Python'] 2902435496128
>>> l1.insert(30,"Rossum") # Most IMP
>>> print(l1,id(l1))----------[10, 20, 30, 'Python', 'Rossum'] 2902435496128
------------------------------------------------------------------------------------------------------------------------------
3) remove() Based on Value
=>Syntax: listobj.remove(Value)
=>This Function is used for removing First Occurence of The specific value from list object.
=>If the specific value does not exist in list object then we get ValueError
Examples:
>>> l1=[10,20,30,10,40,50,60]
>>> print(l1,id(l1))-------------[10, 20, 30, 10, 40, 50, 60] 2902431529344
>>> l1.remove(20)
>>> print(l1,id(l1))---------------[10, 30, 10, 40, 50, 60] 2902431529344
>>> l1.remove(10)
>>> print(l1,id(l1))-----------[30, 10, 40, 50, 60] 2902431529344
>>> l1.remove(50)
>>> print(l1,id(l1))-------------[30, 10, 40, 60] 2902431529344
>>> l1.remove(100)---------ValueError: list.remove(x): x not in list
-----------------------------------------
>>> l1=[]
>>> l1.remove(3)--------------ValueError: list.remove(x): x not in list
>>> list().remove(100)------ValueError: list.remove(x): x not in list
------------------------------------------------------------------------------------------------------------------------------
4) pop(index): Based Index
Syntax: listobj.pop(Index)
=>This Function is used for removing the element of listobj based Index.
=>If index value is invalid then we get IndexError
Examples:
>>> l1=[10,20,10,30,40,50,60,30]
>>> print(l1,id(l1))-------------[10, 20, 10, 30, 40, 50, 60, 30] 2902435496128
>>> l1.pop(2)-----------10
>>> print(l1,id(l1))----------[10, 20, 30, 40, 50, 60, 30] 2902435496128
>>> l1.pop(-1)---------------30
>>> print(l1,id(l1))-------------[10, 20, 30, 40, 50, 60] 2902435496128
>>> l1.pop(2)---------------30
>>> print(l1,id(l1))------------[10, 20, 40, 50, 60] 2902435496128
-----------------------
>>> list().pop(4)--------------IndexError: pop from empty list
>>> [].pop(3)-----------------IndexError: pop from empty list
------------------------------------------------------------------------------------------------------------------------------
5) pop() :
=>Syntax:- list.pop()
=>This Function is used for Removing Last Element of List object
=>When we call pop() on empty list then we get IndexError
23
Examples:
>>> lst=[10,"Rossum",45.67,True,2+3j]
>>> print(lst,type(lst))-------------------[10, 'Rossum', 45.67, True, (2+3j)] <class 'list'>
>>> lst.pop()----------(2+3j)
>>> print(lst,type(lst))----------[10, 'Rossum', 45.67, True] <class 'list'>
>>> lst.pop()------------True
>>> print(lst,type(lst))-------------[10, 'Rossum', 45.67] <class 'list'>
>>> lst.pop()----------45.67
>>> print(lst,type(lst))-------------[10, 'Rossum'] <class 'list'>
>>> lst.pop()-----------'Rossum'
>>> print(lst,type(lst))-----------[10] <class 'list'>
>>> lst.pop()---------------10
>>> print(lst,type(lst))-------------[] <class 'list'>
>>> lst.pop()----------------IndexError: pop from empty list
>>> list().pop()-------------IndexError: pop from empty list
-------------------------------------------------
>>> lst=[10,20,30,40,50]
>>> print(lst)----------------[10, 20, 30, 40, 50]
>>> lst.insert(2,300)
>>> print(lst)------------------[10, 20, 300, 30, 40, 50]
>>> lst.pop()----------------50
------------------------------------------------------------------------------------------------------------------------------
NOTE: del operator
=>del operator is used for deleting Elements of any mutable object either based on Index or
Based on Slicing or Total Object.
=>Syntax1: del object[Index]
del object[Begin:End:Step]
del object
=>With "del" operator we can't delete Immutable Content But we can delete complete
Immutable Object.
Examples:
>>> lst=[10,"Rossum",45.67,True,2+3j,"Python"]
>>> print(lst)--------------------[10, 'Rossum', 45.67, True, (2+3j), 'Python']
>>> del lst[3] # Deleting Based on Index
>>> print(lst)-------------------[10, 'Rossum', 45.67, (2+3j), 'Python']
>>> del lst[2:4] # Deleting Based on Slicing
>>> print(lst)-----------------------[10, 'Rossum', 'Python']
>>> del lst # Deleting Entire Object
>>> print(lst)-----------------NameError: name 'lst' is not defined. Did you mean: 'list'?
-------------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s),id(s))----------------PYTHON <class 'str'> 2073554063472
>>> s=s+"Prog"
>>> print(s,type(s),id(s))-----------------PYTHONProg <class 'str'> 2073554063280
>>> del s[0]------------------------TypeError: 'str' object doesn't support item deletion
>>> del s[0:3]--------------------TypeError: 'str' object does not support item deletion
>>> del s # Deleting Immutable object
>>> s-------------------------NameError: name 's' is not defined
>>>
------------------------------------------------------------------------------------------------------------------------------
6) copy()
=>Syntax: object2=object1.copy()
24
=>This Function is used for Copying the content of one object into another object (Implementation of
Sallow Copy )

Examples: Sallow Copy


>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))---------------------[10, 'Rossum'] 2073549864512
>>> l2=l1.copy() # Shallow Copy
>>> print(l2,id(l2))--------------------[10, 'Rossum'] 2073554063744
>>> l1.append("Python")
>>> l1.append("Python")
>>> l2.insert(1,"PSF")
>>> print(l1,id(l1))----------------[10, 'Rossum', 'Python', 'Python'] 2073549864512
>>> print(l2,id(l2))----------------[10, 'PSF', 'Rossum'] 2073554063744
-----------------------------------------------------------------------------------------------------------------------------
Examples:----Deep Copy
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))-----------------------[10, 'Rossum'] 2073554059392
>>> l2=l1 # Deep Copy
>>> print(l2,id(l2))------------------------[10, 'Rossum'] 2073554059392
>>> l1.append("Python")
>>> print(l1,id(l1))------------------------[10, 'Rossum', 'Python'] 2073554059392
>>> print(l2,id(l2))------------------------[10, 'Rossum', 'Python'] 2073554059392
>>> l2.insert(2,"PSF")
>>> print(l1,id(l1))-----------------------[10, 'Rossum', 'PSF', 'Python'] 2073554059392
>>> print(l2,id(l2))-----------------------[10, 'Rossum', 'PSF', 'Python'] 2073554059392
-------------------------------------------------------------------------------------------------------------------------
NOTE:- Slice Based Copy
------------------------------------------------------------------------------------------------------------------------
>>> lst1=[10,20,30,40,50,60]
>>> print(lst1,id(lst1))---------------[10, 20, 30, 40, 50, 60] 2073692289216
>>> lst2=lst1[0:3] # Slice Based Copy
>>> print(lst2,id(lst2))---------------------[10, 20, 30] 2073692289792
>>> lst2.append(12.34)
>>> lst1.append(70)
>>> print(lst1,id(lst1))-------------------[10, 20, 30, 40, 50, 60, 70] 2073692289216
>>> print(lst2,id(lst2))------------------[10, 20, 30, 12.34] 2073692289792
>>>
>>> lst3=lst1[::] # Slice Based Copy
>>> print(lst3,id(lst3))-----------------[10, 20, 30, 40, 50, 60, 70] 2073686948288
>>> lst3.insert(1,"KVR")
>>> lst1.append(80)
>>> print(lst1,id(lst1))---------------[10, 20, 30, 40, 50, 60, 70, 80] 2073692289216
>>> print(lst3,id(lst3))---------------[10, 'KVR', 20, 30, 40, 50, 60, 70] 2073686948288

Copy Techniques in Python


=>In Python Programming, we have 2 types of Copy Techniques. They are
1. Shallow Copy 2. Deep Copy

1. Shallow Copy
=>The Properties of Shallow Copy are
a) Initial Content of Both the Objects are Same.
25
b) Both the Objects Memory Address are Different
c) Modifications are Indepedent ( Whatever the modifications we do on any one
object they are not reflecting another object)

=>To Implement Shallow Copy, we use copy().


=>Syntax: object2=object1.copy()
Examples:
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))---------------------[10, 'Rossum'] 2073549864512
>>> l2=l1.copy() # Shallow Copy
>>> print(l2,id(l2))--------------------[10, 'Rossum'] 2073554063744
>>> l1.append("Python")
>>> l1.append("Python")
>>> l2.insert(1,"PSF")
>>> print(l1,id(l1))----------------[10, 'Rossum', 'Python', 'Python'] 2073549864512
>>> print(l2,id(l2))----------------[10, 'PSF', 'Rossum'] 2073554063744

2. Deep Copy
=>The Properties of Deep Copy are
a) Initial Content of Both the Objects are Same.
b) Both the Objects Memory Address are Same
c) Modifications are Depedent ( Whatever the modifications we do on any one
object they are reflecting to another object)

=>To Implement Deep Copy, we use Assignment Operator ( = )


=>Syntax: object2 = object1

Examples:
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))-----------------------[10, 'Rossum'] 2073554059392
>>> l2=l1 # Deep Copy
>>> print(l2,id(l2))------------------------[10, 'Rossum'] 2073554059392
>>> l1.append("Python")
>>> print(l1,id(l1))------------------------[10, 'Rossum', 'Python'] 2073554059392
>>> print(l2,id(l2))------------------------[10, 'Rossum', 'Python'] 2073554059392
>>> l2.insert(2,"PSF")
>>> print(l1,id(l1))-----------------------[10, 'Rossum', 'PSF', 'Python'] 2073554059392
>>> print(l2,id(l2))-----------------------[10, 'Rossum', 'PSF', 'Python'] 2073554059392
-------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------
7) count():
Syntax:- listobj.count(Value)
=>This Function is used for Counting Number of Occurences of a Specified Element.
=>If the Specified Element does not exist in list object then we get 0
Examples:
>>> lst=[10,20,30,40,10,20,10,60]
>>> print(lst)
[10, 20, 30, 40, 10, 20, 10, 60]
>>> lst.count(10)-----------------3
>>> len(lst)----------------------8
26
>>> lst.count(20)---------------2
>>> lst.count(30)----------------1
>>> lst.count(300)--------------0
>>> lst.count("H")-------------0
---------------------------------------------------
>>> list().count(10)---------------0
>>> [].count("")-------------------0
-------------------------------------------------------------------------------------------------
8) index()
=>Syntax:- listobj.index(Value)
=>This Function is used for finding Index of First Occurence of Sppecified Element.
=>If the Sppecified Element not existing in list object then we get ValueError.
Examples:
>>> lst=[10,20,30,10,60,70,80,20,45]
>>> print(lst)------------------[10, 20, 30, 10, 60, 70, 80, 20, 45]
>>> lst.index(10)-------------0
>>> lst.index(20)----------1
>>> lst.index(60)------------4
>>> lst.index(45)-----------8
>>> lst.index(145)--------------ValueError: 145 is not in list
>>> list().index("KVR")---------ValueError: 'KVR' is not in list
>>> [10,20,30].index(10)---------0
>>> [10,20,30].index(100)--------ValueError: 100 is not in list
>>> [10,20,30].index("10")-----------ValueError: '10' is not in list
-------------------------------------------------------------------------------------------------
9) reverse()
=>Syntax: listobj.reverse()
=>This Function is used for obtaining reverse the content of listobject (nothing but front to
back and back to front)
Examples:
>>> l1=[10,20,30,-4,-5,100,12,45]
>>> print(l1,id(l1))------------------------[10, 20, 30, -4, -5, 100, 12, 45] 2670070726208
>>> l1.reverse()
>>> print(l1,id(l1))-----------------------[45, 12, 100, -5, -4, 30, 20, 10] 2670070726208
>>> l1=["Python","java","R","DS"]
>>> print(l1,id(l1))------------------------['Python', 'java', 'R', 'DS'] 2670074921088
>>> l1.reverse()
>>> print(l1,id(l1))------------------------['DS', 'R', 'java', 'Python'] 2670074921088
-------------------------------------------------------------------------------------------------
10) sort()
=>This function is used for sorting the Homogeneous (Similar ) data either in Ascending
Order (reverse = False) or in Descending Order (reverse=True)
=>When we call sort() on list object where it contains Hetrogeneous (different) data then we
get TypeError.
=>Syntax: listobj.sort() ---- Display the data in Ascending Order
=>Syntax: listobj.sort(reverse=False)---Display the data in Ascending Order(default value of reverse
is False)
=>Syntax: listobj.sort(reverse=True)---Display the data in Descending Order
Examples:
>>> l1=[10,-4,23,15,56,3,-5,34,0]
>>> print(l1,id(l1))---------------[10, -4, 23, 15, 56, 3, -5, 34, 0] 2670070726208
>>> l1.sort()
27
>>> print(l1,id(l1))---------------------[-5, -4, 0, 3, 10, 15, 23, 34, 56] 2670070726208
>>> l2=["Travis","Kinney","Rossum","Trump","Biden","Dennis","Anil"]
>>> print(l2)----['Travis', 'Kinney', 'Rossum', 'Trump', 'Biden', 'Dennis', 'Anil']
>>> l2.sort()
>>> print(l2)----['Anil', 'Biden', 'Dennis', 'Kinney', 'Rossum', 'Travis', 'Trump']
--------------------------------------------------------
>>> l3=[10,"Rossum",34.56,True]
>>> l3.sort()---------TypeError: '<' not supported between instances of 'str' and 'int'
-----------------------------
>>> l2=["Travis","Kinney","Rossum","Trump","Biden","Dennis","Anil"]
>>> print(l2)---------['Travis', 'Kinney', 'Rossum', 'Trump', 'Biden', 'Dennis', 'Anil']
>>> l2.sort()
>>> print(l2)-------------['Anil', 'Biden', 'Dennis', 'Kinney', 'Rossum', 'Travis', 'Trump']
>>> l2.reverse()
>>> print(l2)------------['Trump', 'Travis', 'Rossum', 'Kinney', 'Dennis', 'Biden', 'Anil']
----------------------------------
>>> l1=[10,-4,23,15,56,3,-5,34,0]
>>> print(l1,id(l1))-----------------[10, -4, 23, 15, 56, 3, -5, 34, 0] 2670074921088
>>> l1.sort()
>>> print(l1,id(l1))------------------[-5, -4, 0, 3, 10, 15, 23, 34, 56] 2670074921088
>>> l1.reverse()
>>> print(l1,id(l1))--------------[56, 34, 23, 15, 10, 3, 0, -4, -5] 2670074921088
-------------------------
>>> l1=[10,-4,23,15,56,3,-5,34,0]
>>> print(l1,id(l1))----------------[10, -4, 23, 15, 56, 3, -5, 34, 0] 2670070726208
>>> l1.sort(reverse=True)
>>> print(l1,id(l1))----------------[56, 34, 23, 15, 10, 3, 0, -4, -5] 2670070726208
--------------------------------------------------------------
>>> l1=[10,-4,23,15,56,3,-5,34,0]
>>> print(l1,id(l1))
[10, -4, 23, 15, 56, 3, -5, 34, 0] 2670070726208
>>> l1.sort(reverse=False) # OR l1.sort()
>>> print(l1,id(l1))------------------[-5, -4, 0, 3, 10, 15, 23, 34, 56] 2670070726208
----------------------
>>> l1=[10,-4,23,15,56,3,-5,34,0]
>>> print(l1,id(l1))-------------[10, -4, 23, 15, 56, 3, -5, 34, 0] 2670074921088
>>> l1.sort()
>>> print(l1,id(l1))-------------[-5, -4, 0, 3, 10, 15, 23, 34, 56] 2670074921088
---------------------------------------------------------------------------------------------------------------------
11) extend()
=> Syntax: listobj1.extend(listobj2)
=>This Function is used for extending the functionality of listobj1 with the values of listobj2.
=>At any point time, extend() takes one list object as argument
=>If we want extend the functionality of one list object with multiple objects then we can
use + operator.
=>Syntax:- listobj1=listobj1+listobj2+......listobj-n
Examples:
>>> l1=[10,20,30] >>> l2=["RS","TR","SD"] >>> l1.extend(l2)
>>> print(l1)->[10, 20, 30, 'RS', 'TR', 'SD'] >>> print(l2)->['RS', 'TR', 'SD']
>>> l1=[10,20,30] >>> l2=["RS","TR","SD"] >>> l2.extend(l1)
>>> print(l1)->[10, 20, 30] >>> print(l2)->['RS', 'TR', 'SD', 10, 20, 30]
>>> l1=[10,20,30] >>> l2=["RS","TR","SD"] >>> l3=["Python","R"]
28
>>> l1.extend(l2,l3)->TypeError: list.extend() takes exactly one argument (2 given)
NOTE:
>>> l1=l1+l2+l3 >>> print(l1)->[10, 20, 30, 'RS', 'TR', 'SD', 'Python', 'R']
----------------------------------------------------------------------------------------
11) clear()
=>Syntax: listobj.clear()
=>This Function is used removing all the elements of non-empotylist
Examples:
>>> l1=[10,-4,23,15,56,3,-5,34,0] >>> print(l1,id(l1))->[10, -4, 23, 15, 56, 3, -5, 34, 0]
2670074921088 >>> len(l1)->9
>>> l1.clear() >>> print(l1,id(l1))->[] 2670074921088 >>> len(l1)->0
>>> print([].clear())->None >>> print(list().clear())->None

Inner List OR Nested List


=>The Process of defining one list in another list is called Inner or Nested List
=>Syntax: listobj=[Val1, Val2.......[Val11,Val12..] , [ Val21,Val22.....], Val-n ]

=>here [Val11,Val12..] is one Inner List,[ Val21,Val22.....] is another Inner list


=>[Val1, Val2......., Val-n ] is called Outer List
Examples:
>>> sinfo=[10,"Rossum",[19,17,20] , [78,77,79] ,"OUCET" ]
>>> sinfo[0]--------------------10
>>> sinfo[-1]------------------- 'OUCET'
>>> sinfo[1]--------------------- 'Rossum'
>>> sinfo[2]--------------------[19, 17, 20]
>>> print(sinfo[2],type(sinfo[2]))---------------[19, 17, 20] <class 'list'>
>>> print(sinfo[2],type(sinfo[2]), type(sinfo))--------[19, 17, 20] <class 'list'> <class 'list'>
>>> print(sinfo[-2],type(sinfo[-2]), type(sinfo))--------[78, 77, 79] <class 'list'> <class 'list'>
>>> print(sinfo[0],type(sinfo[0]), type(sinfo))---------10 <class 'int'> <class 'list'>
-----------------------------------------
>>> sinfo=[10,"Rossum",[19,17,20] , [78,77,79] ,"OUCET" ]
>>> print(sinfo)------------[10, 'Rossum', [19, 17, 20], [78, 77, 79], 'OUCET']
>>> sinfo[2][-1]------------20
>>> sinfo[2][::]-------------[19, 17, 20]
>>> sinfo[2][::-1]------------[20, 17, 19]
>>> sinfo[2][2]=18
>>> print(sinfo)---------------[10, 'Rossum', [19, 17, 18], [78, 77, 79], 'OUCET']
>>> sinfo[2].sort()
>>> print(sinfo)---------------[10, 'Rossum', [17, 18, 19], [78, 77, 79], 'OUCET']
>>> sinfo[-2].sort(reverse=True)
>>> print(sinfo)-----------------[10, 'Rossum', [17, 18, 19], [79, 78, 77], 'OUCET']
>>> sinfo[2][0:2]--------------[17, 18]
>>> sinfo[2][::2]--------------[17, 19]
>>> sinfo[-3].remove(18)
>>> print(sinfo)-----------------[10, 'Rossum', [17, 19], [79, 78, 77], 'OUCET']
>>> del sinfo[-2][1:]
>>> print(sinfo)---------------[10, 'Rossum', [17, 19], [79], 'OUCET']
>>> sinfo[2].clear()
>>> print(sinfo)-------------[10, 'Rossum', [], [79], 'OUCET']
>>> del sinfo[2]
>>> print(sinfo)----------------[10, 'Rossum', [79], 'OUCET']
>>> del sinfo[-2]
29
>>> print(sinfo)--------------------[10, 'Rossum', 'OUCET']
>>> im=[16,17,14]
>>> sinfo.insert(2,im)
>>> print(sinfo)------------------------[10, 'Rossum', [16, 17, 14], 'OUCET']
>>> sinfo.insert(3,[67,74,66])
>>> print(sinfo)--------------------[10, 'Rossum', [16, 17, 14], [67, 74, 66], 'OUCET']
------------------------------------------------------------------
>>> print(sinfo)------------[10, 'Rossum', [16, 17, 14], [67, 74, 66], 'OUCET']
>>> k=["PYTHON","R"]
>>> sinfo[2].insert(1,k)
>>> print(sinfo)-----------[10, 'Rossum', [16, ['PYTHON', 'R'], 17, 14], [67, 74, 66], 'OUCET']
------------------------------------------------------------------------------------------------------
2) tuple
=>'tuple' of the one of the pre-defined class and treated as list data type.
=>The purpose of tuple data type is that "To store Collection of Values or multiple
values either of Same type or different type or both the types with unique and duplicate."
=>The elements of tuple must be stored within braces ( ) and the elements must separated by comma.
=>An object of tuple maintains insertion Order.
=>On the object of tuple, we can perform both Indexing and Slicing.
=>An object of tuple belongs to immutable bcoz tuple' object does not support item
assignment
=>To convert any other object into tuple type object, we use tuple()
Syntax:- tupleobject=tuple(another object)
=>We can create two types of tuple objects. They are
a) empty tuple
b) non-empty tuple
a) empty tuple:
-------------------------
=>An empty tuple is one, which does not contain any elements and length is 0
=>Syntax:- tupleobj=()
or
tupleobj=tuple()
Examples:
-----------------
>>> t=()
>>> print(t,type(t),id(l))------------ () <class 'tuple'> 2722448959680
>>> len(t)----------- 0
>>> l1=tuple()
>>> print(l1,type(l1),id(l1))------------- () <class 'tuple'> 2722452472064
>>> len(l1)------------------ 0
--------------------------------------------------------------------------
b) non-empty tuple:
--------------------------------
=>A non-empty tuple is one, which contains elements and length is >0
Syntax:- tplobj=(val1,val2...val-n)
(OR)
tplobj=val1,val2...val-n
-----------------------------------------------------------------------------------------------------------------------------
Note: The Functionality of tuple is exactly similar to list but an object of list belongs to mutable and an
object of tuple belongs to immutable.
-----------------------------------------------------------------------------------------------------------------------------
Examples:
30
--------------
>>> t1=(10,20,30,40,10,10)
>>> print(t1,type(t1))---------------(10, 20, 30, 40, 10, 10) <class 'tuple'>
>>> t2=(10,"Ram",34.56,True,2+4.5j)
>>> print(t2,type(t2),id(t2))-------------(10, 'Ram', 34.56, True, (2+4.5j)) <class 'tuple'>
2328568492208
>>> t2[0]----------------10
>>> t2[1]------------------'Ram'
>>> t2[-1]-----------------(2+4.5j)
>>> t2[1:4]---------------------('Ram', 34.56, True)
>>> t2[2]=56.78-----------TypeError: 'tuple' object does not support item assignment
--------------------------------------------------
>>> t1=()
>>> print(t1,len(t1))------------------() 0
(OR)
>>> t2=tuple()
>>> print(t2,len(t2))--------------------() 0
-----------------------------------------------------------
>>> l1=[10,"Rossum"]
>>> print(l1,type(l1))-------------------[10, 'Rossum'] <class 'list'>
>>> t1=tuple(l1)
>>> print(t1,len(t1))---------------(10, 'Rossum') 2
-------------------------------------------------------------------------------
>>> a=10,"KVR","Python",True # without braces ( )
>>> print(a,type(a))---------------------------(10, 'KVR', 'Python', True) <class 'tuple'>
>>> a=10,
>>> print(a,type(a))---------------(10,) <class 'tuple'>
>>> a=10
>>> print(a,type(a))-----------10 <class 'int'>
>>> t=tuple(a)-------------TypeError: 'int' object is not iterable
>>> t=tuple(a,)------------TypeError: 'int' object is not iterable
>>> t=tuple((a))-----------TypeError: 'int' object is not iterable
>>> t=(a,) # correct conversion
>>> print(t,type(t))----------------(10,) <class 'tuple'>
>>> print(a,type(a))-----------10 <class 'int'>
---------------------------------------------------X----------------------------------------------------
Inner tuple OR Tuple List
=>The Process of defining one tuple in another tuple is called Inner or Nested tuple
=>Syntax: tupleobj=(Val1, Val2.......(Val11,Val12..) , ( Val21,Val22.....), Val-n)

=>here (Val11,Val12..) is one Inner tuple


=>Here ( Val21,Val22.....) is another Inner tuple

=>(Val1, Val2......., Val-n ) is called Outer tuple

NOTE:
-------------
=>We can define One Tuple Inside of Another Tuple
=>We can define One List Inside of Another List
=>We can define One Tuple Inside of Another List
=>We can define One List Inside of Another Tuple
--------------------------------------------------------------------------------------------------------------------
31
Examples
---------------------------
>>> t1=(10,"Rossum",(15,18,17),(66,67,56),"OUCET")
>>> print(t1,type(t1))-------------(10, 'Rossum', (15, 18, 17), (66, 67, 56), 'OUCET') <class 'tuple'>
>>> t1[2]--------------(15, 18, 17)
>>> print(t1[2],type(t2))------------(15, 18, 17) <class 'tuple'>
>>> print(t1[-2],type(t2))------------(66, 67, 56) <class 'tuple'>
-------------------------------
>>> t1=(10,"Rossum",[15,18,17],(66,67,56),"OUCET")
>>> print(t1,type(t1))------(10, 'Rossum', [15, 18, 17], (66, 67, 56), 'OUCET') <class 'tuple'>
>>> print(t1[2],type(t1[2]))-----[15, 18, 17] <class 'list'>
>>> print(t1[3],type(t1[3]))-------(66, 67, 56) <class 'tuple'>
>>> t1[2].insert(1,16)
>>> print(t1,type(t1))------(10, 'Rossum', [15, 16, 18, 17], (66, 67, 56), 'OUCET') <class 'tuple'>
>>> t1[2].sort(reverse=True)
>>> print(t1,type(t1))--------(10, 'Rossum', [18, 17, 16, 15], (66, 67, 56), 'OUCET') <class 'tuple'>
------------------------------------
>>> l1=[10,"Rossum",[15,18,17],(66,67,56),"OUCET"]
>>> print(l1,type(l1))------------[10, 'Rossum', [15, 18, 17], (66, 67, 56), 'OUCET'] <class 'list'>
>>> l1[2].remove(18)
>>> print(l1,type(l1))----------[10, 'Rossum', [15, 17], (66, 67, 56), 'OUCET'] <class 'list'>
=================================X=========================================

Special Case:
-----------------------
sorted():
----------------
=>It is one of the general pre-defined function and is used for Sorting the elements of tuple
(in this case) and gives the sorted elements in th form of list(But Sorted Elements will not place
in tuple bcoz tuple is immutable).
Syntax: sorted(tuple object)
(OR)
listobj=sorted(tupleobj)

--------------------
Examples:
--------------------
>>> t1=(12,45,-3,3,0,14)
>>> print(t1,type(t1))-------------------(12, 45, -3, 3, 0, 14) <class 'tuple'>
>>> t1.sort()-------------AttributeError: 'tuple' object has no attribute 'sort'
>>> sorted(t1)---------- [-3, 0, 3, 12, 14, 45]
>>> print(t1,type(t1))-----------(12, 45, -3, 3, 0, 14) <class 'tuple'>
>>> x=sorted(t1)
>>> print(x,type(x))--------------[-3, 0, 3, 12, 14, 45] <class 'list'>
(OR)
>>> t1=(12,45,-3,3,0,14)
>>> print(t1,type(t1))-------------(12, 45, -3, 3, 0, 14) <class 'tuple'>
>>> l1=list(t1)
>>> print(l1,type(l1))-------------[12, 45, -3, 3, 0, 14] <class 'list'>
>>> l1.sort()
>>> print(l1,type(l1))-----------[-3, 0, 3, 12, 14, 45] <class 'list'>
>>> t1=tuple(l1)

32
>>> print(t1,type(t1))------(-3, 0, 3, 12, 14, 45) <class 'tuple'>
-------------------------------------------------------------------------------------
Set Categery Data Types( Collections Data Types or Data Structures)
=>The purpose of Set Categery Data Types is that " To store Collection or multiple values either
of same type or different type or both the types with Unique Values ( No duplicates are allowed)".
=>We have 2 data types in Set Categery. They are
1. set (mutable and immutable ) 2. frozenset (immutable )
1. set
=>"set" is one of the pre-defined class and treated as set data type.
=>The purpose of set data type is that " To store Collection or multiple values either of same
type or different type or both the types with Unique Values ( No duplicatesd are allowed)".
=>The elements of set must be organized within curly braces { } and elements must separated
by comma,
=>An object of set does not maintain insertion order bcoz PVM displays any order of multiple
possibilities.
=>On the object of set, we can't perform Indexing and slicing Operations bcoz set object does
not maintain Insertion order.
=>An object of set belongs to immutable (bcoz of 'set' object does not support item
assignment) and mutable ( bcoz in the case of add() ).
=>By using set class, we can two types of set objects. They are
a) empty set
b) non-empty set
a) empty set:
=>An empty set is one, which does not contain any elements and whose length is 0
=>Syntax:- setobj=set()

b) non-empty set:
=>A non-empty set is one, which contains elements and whose length is >0
=>Syntax:- setobj={val1,val2...val-n}

=>To convert one type of object into set type object, we use set()
Syntax: setobj=set(obj)
--------------------------------------------------------------------------------------------------------------------
Examples:
>>> s1={10,20,30,40,50,10,10,20,75}
>>> print(s1,type(s1))-----------------{50, 20, 40, 10, 75, 30} <class 'set'>
>>> s1={10,20,25,35,10,20}
>>> print(s1,type(s1))-------------------{25, 10, 35, 20} <class 'set'>
>>> s1[0]----------------TypeError: 'set' object is not subscriptable
>>> s1[0:3]--------------TypeError: 'set' object is not subscriptable
------------------------------------------------------------
>>> s1={10,20,30,40,50}
>>> print(s1,id(s1))-------------------------------{50, 20, 40, 10, 30} 1473821509440
>>> s1[0]=100-------------TypeError: 'set' object does not support item assignment
>>> s1.add("KVR")
>>> print(s1,id(s1))------------------{50, 20, 40, 10, 'KVR', 30} 1473821509440
-------------------------------------------------------------------------------------------
>>> s1=set()
>>> print(s1,type(s1))------------------{} <class 'set'>
>>> len(s1)------------0
>>> s2={10,20,30,10,20}
>>> print(s2,type(s2))---------------{10, 20, 30} <class 'set'>
33
>>> len(s2)-------------------3
--------------------------------------------------------------------------------
>>> l1=[10,20,10,20,"Python",23.45]
>>> s1=set(l1)
>>> print(s1)-----------------{10, 20, 23.45, 'Python'}
>>> t1=tuple(s1)
>>> print(t1,type(t1))------------(10, 20, 23.45, 'Python') <class 'tuple'>
>>> t1=list(s1)
>>> print(t1,type(t1))------------[10, 20, 23.45, 'Python'] <class 'list'>
==============================X====================================
==========================================
pre-defined functions in set
==========================================
=>on the object of set, we can perform different type of Operations by using pre-defined
functions in set object.
-------------------------------------------------------------------------------------------------------------------------
1) add()
-------------------------------------------------------------------------------------------------------------------------
=>This Function is used for adding the elements to set object.
=>Syntax: setobj.add(Value)
--------------------------------
Examples:
---------------------------------
>>> s1={10,20,30}
>>> print(s1,type(s1),id(s1))--------------{10, 20, 30} <class 'set'> 1691649314592
>>> s1.add(12.34)
>>> print(s1,type(s1),id(s1))-------------{10, 20, 12.34, 30} <class 'set'> 1691649314592
>>> s1.add("python")
>>> print(s1,type(s1),id(s1))------------{10, 12.34, 'python', 20, 30} <class 'set'> 1691649314592
>>> s2=set()
>>> print(s2,type(s2),id(s2))----------set() <class 'set'> 1691645340672
>>> s2.add(100)
>>> s2.add("Rajesh")
>>> s2.add("Kasif")
>>> print(s2,type(s2),id(s2))--------{100, 'Kasif', 'Rajesh'} <class 'set'> 1691645340672
>>> s2.add(23.45)
>>> print(s2,type(s2),id(s2))-----{100, 23.45, 'Kasif', 'Rajesh'} <class 'set'> 1691645340672
------------------------------------------------------------------------------------------------------------------------
2) remove()
------------------------------------------------------------------------------------------------------------------------
=>Syntax:- setobj.remove(Value)
=>This Function is used for removing the element from set object.
=>The element / value does not exist in setobject then we get KeyError( bcoz all the elements
of set are Unique and they are called Keys)
----------------
Examples:
---------------
>>> s1={10,"Rajesh",34.56,400,True,2+3j}
>>> print(s1,type(s1))--------{400, True, 34.56, 'Rajesh', 10, (2+3j)} <class 'set'>
>>> print(s1,type(s1),id(s1))---{400, True, 34.56, 'Rajesh', 10, (2+3j)} <class 'set'>1691649315936
>>> s1.remove(34.56)
>>> print(s1,type(s1),id(s1))----{400, True, 'Rajesh', 10, (2+3j)} <class 'set'> 1691649315936
34
>>> s1.remove(True)
>>> print(s1,type(s1),id(s1))---{400, 'Rajesh', 10, (2+3j)} <class 'set'> 1691649315936
>>> s1.remove("Rajesh")
>>> print(s1,type(s1),id(s1))----{400, 10, (2+3j)} <class 'set'> 1691649315936
>>> s1.remove("KVR")------KeyError: 'KVR'
>>> set().remove(10)-----------KeyError: 10
------------------------------------------------------------------------------------------------------------------------
3) discard()
------------------------------------------------------------------------------------------------------------------------
=>Syntax: setobj.discard(value)
=>This Function is used for removing theelement from set object.
=>The element / value does not exist in setobject then we never get KeyError
Examples:
----------------------
>>> s1={10,20,30,40,50,60,70,10}
>>> print(s1,type(s1))-------------------{50, 20, 70, 40, 10, 60, 30} <class 'set'>
>>> s1.discard(50)
>>> print(s1,type(s1))-------------------{20, 70, 40, 10, 60, 30} <class 'set'>
>>> s1.discard(10)
>>> print(s1,type(s1))-------------------{20, 70, 40, 60, 30} <class 'set'>
>>> s1.discard(100) # we never get KeyError
>>> print(s1,type(s1))-------------------{20, 70, 40, 60, 30} <class 'set'>
>>> s1.discard("Python") # we never get KeyError
>>> s1.remove("Python")-----------KeyError: 'Python'
------------------------------------------------------------------------------------------------------------------------
4) clear()
------------------------------------------------------------------------------------------------------------------------
=>Syntax: setobj.clear()
=>This function is used for removing all the elements of set object.
Examples:
------------------
>>> s1={10,20,30,40,50,60,70,10}
>>> print(s1,type(s1))---------------------{50, 20, 70, 40, 10, 60, 30} <class 'set'>
>>> len(s1)------------------------7
>>> s1.clear()
>>> print(s1,type(s1))-----------------set() <class 'set'>
>>> len(s1)------------------0
>>> print( set().clear() )------------None
------------------------------------------------------------------------------------------------------------------------
5) copy() -----------Shallow Copy
------------------------------------------------------------------------------------------------------------------------
Syntax: setobj2=setobj1.copy()
=>This Function is used for copying the content of one set object into another set object
-------------------
=>Examples:
--------------------
>>> s1={10,20,30,40,50,60,70,10}
>>> print(s1,type(s1),id(s1))-------------{50, 20, 70, 40, 10, 60, 30} <class 'set'> 2424304921600
>>> s2=s1.copy()
>>> print(s2,type(s2),id(s2))----------{50, 20, 70, 40, 10, 60, 30} <class 'set'> 2424308895072
>>> s1.add(12.34)
>>> s2.add("Python")
35
>>> print(s1,type(s1),id(s1))------{50, 20, 70, 40, 10, 60, 12.34, 30} <class 'set'> 2424304921600
>>> print(s2,type(s2),id(s2))---{50, 20, 'Python', 70, 40, 10, 60, 30} <class 'set'> 2424308895072
------------------------------------------------------------------------------------------------------------------------
6) isdisjoint()
------------------------------------------------------------------------------------------------------------------------
=>Syntax: setobj1.isdisjoin(s2)

=>This Function returns True Provided there is no common eleement between setobj1 and
setobj2.
=>This Function returns False Provided there is atleast common eleement between setobj1
and setobj2.
-----------------
Examples:
----------------
>>> s1={10,20,30,40}
>>> s2={"Apple","Mango","kiwi"}
>>> s3={10,50,60}
>>> s1.isdisjoint(s2)--------------True
>>> s1.isdisjoint(s3)--------------False
------------------------------------------------------------------------------------------------------------------------
7) issuperset()
------------------------------------------------------------------------------------------------------------------------
Syntax: setobj1.issuperset(setobj2)
=>This Function return True provided all elements setobj2 must present setobj1
OR
setobj1 must contains all elements of setobj2

Examples:
----------------
>>> s1={10,20,30,40}
>>> s2={10,20}
>>> s3={10,20, "Apple","Mango","kiwi"}
>>> s1.issuperset(s2)----------True
>>> s1.issuperset(s3)---------False
------------------------------------------------------------------------------------------------------------------------
8) issubset()
------------------------------------------------------------------------------------------------------------------------
Syntax: setobj1.issubset(setobj2)
=>This Function return True provided all elements setobj1 must present setobj2
OR
setobj2 must contains all elements of setobj1
Examples:
----------------
>>> s1={10,20,30,40}
>>> s2={10,20}
>>> s3={10,20, "Apple","Mango","kiwi"}
>>> s2.issubset(s1)---------True
>>> s3.issubset(s1)----------False
>>> s3.issubset(s2)---------False
>>> s2.issubset(s3)-------True
------------------------------------------------------------------------------------------------------------------------
9) union()
36
------------------------------------------------------------------------------------------------------------------------
Syntax:- setobj1.union(setobj2)
(OR)
setobj3=setob1.union(setobj2)
=>This is used for for obtaining all Unique Elements of setobj1 and setobj2 and result
unique values placed in setobj3.

Examples:
---------------
>>> s1={10,20,30,40}
>>> s2={15,10,25}
>>> s3=s1.union(s2)
>>> print(s1)-----------{40, 10, 20, 30}
>>> print(s2)----------{25, 10, 15}
>>> print(s3)-----------{20, 40, 25, 10, 30, 15}
--------------------------
>>> print(s1.union(s2))-----------{20, 40, 25, 10, 30, 15}
------------------------------------------------------------------------------------------------------------------------
10) intersection()
------------------------------------------------------------------------------------------------------------------------
Syntax: setobj1.intersection(setobj2)
(OR)
setobj3= setobj1.intersection(setobj2)
=>This function is used for obtaining common elements from setobj1 and setobj2.
---------------
Examples:
----------------
>>> s1={10,20,30,40}
>>> s2={15,10,25}
>>> s3=s1.intersection(s2)
>>> print(s3)------------{10}
>>> s3=s2.intersection(s1)
>>> print(s3)-------------{10}
>>> print(s1.intersection(s2))-------{10}

>>> s1={10,20,30,40}
>>> s2={"Apple","Mango","kiwi"}
>>> print(s1.intersection(s2))------------set()
------------------------------------------------------------------------------------------------------------------------
11)difference()
------------------------------------------------------------------------------------------------------------------------
=>Syntax: setobj1.difference(setobj2)
=>This obtains removes common elements from setobj1 and setobj2 and Takes remaining
elements from setobj1 and place them setobj3.
Examples:
-----------------
>>> s1={10,20,30,40}
>>> s2={10,15,25}
>>> s3=s1.difference(s2)
>>> print(s1)--------{40, 10, 20, 30}
>>> print(s2)-------------{25, 10, 15}
>>> print(s3)---------{40, 20, 30}
37
>>> s4=s2.difference(s1)
>>> print(s4)--------{25, 15}

>>> a = {1, 3 ,5}


>>> b = {2, 4, 6}
>>> c = {1, 2}
>>> print(a)---------{1, 3, 5}
>>> print(b)--------{2, 4, 6}
>>> print(c)-------{1, 2}
>>> d=a.difference(b).difference(c)
>>> print(d)--------{3, 5}
>>> d=a.difference(b,c)
>>> print(d)-------------{3, 5}
------------------------------------------------------------------------------------------------------------------------
12) symmetric_difference()
------------------------------------------------------------------------------------------------------------------------
=>Syntax: setobj1.symmetric_difference(setobj2)
=>This function removes common elements from both setobj1 and setobj2 and Takes
remaining elements from both setobj1 and setobj2 and place them setobj3.
Examples:
----------------
>>> s1={10,20,30,40}
>>> s2={10,15,25}
>>> s3=s1.symmetric_difference(s2)
>>> print(s1)----------{40, 10, 20, 30}
>>> print(s2)--------{25, 10, 15}
>>> print(s3)--------{40, 15, 20, 25, 30}
>>> s3=s2.symmetric_difference(s1)
>>> print(s3)-------------{40, 15, 20, 25, 30}
------------------------------------------------------------------------------------
Use-Case:
------------------
>>> cp={"sachin","kohli","rohit"}
>>> tp={"rossum","saroj","rohit"}
------------------------------------
>>> allcptp=cp.union(tp)
>>> print(allcptp)-----------------{'kohli', 'sachin', 'rohit', 'rossum', 'saroj'}
>>> bothcptp=cp.intersection(tp)
>>> print(bothcptp)--------------{'rohit'}
>>> onlycp=cp.difference(tp)
>>> print(onlycp)-------------{'kohli', 'sachin'}
>>> onlytp=tp.difference(cp)
>>> print(onlytp)-------------{'rossum', 'saroj'}
>>> exclcptp=cp.symmetric_difference(tp)
>>> print(exclcptp)---------------{'sachin', 'rossum', 'kohli', 'saroj'}
----------------------------------------------------------------------------------------------------------
MOST IMP Case:
>>> allcptp=cp|tp # Bitwise OR Operator ( | )
>>> print(allcptp)------{'kohli', 'sachin', 'rohit', 'rossum', 'saroj'}
>>> bothptp=cp&tp # Bitwise AND Operator ( & )
>>> print(bothcptp)---------{'rohit'}
>>> onlycp=cp-tp # Subtract Operator
38
>>> print(onlycp)--------{'kohli', 'sachin'}
>>> onlytp=tp-cp # Subtract Operator
>>> print(onlytp)----------{'rossum', 'saroj'}
>>> exclcptp=cp^tp # Biwise XOR Operator ( ^ )
>>> print(exclcptp)--------{'sachin', 'rossum', 'kohli', 'saroj'}

>>> print({10,20,30} & {10,25,67,34})----------{10}


------------------------------------------------------------------------------------------------------------------------
13) update()
------------------------------------------------------------------------------------------------------------------------
=>Syntax: setobj1.update(setobj2)
=>This Function is used for updating the values of setobj2 with setobj1.
----------------
Examples:
-----------------
>>> s1={10,20,30}
>>> s2={"Python","Java"}
>>> print(s1,id(s1))----------{10, 20, 30} 2424308898432
>>> print(s2,id(s2))----------{'Java', 'Python'} 2424308895072
>>> s1.update(s2)
>>> print(s1,id(s1))----------{20, 'Java', 10, 'Python', 30} 2424308898432
---------------------------------------
>>> s1={10,20,30}
>>> s2={10,20,"Python"}
>>> print(s1,id(s1))---------{10, 20, 30} 2424308896416
>>> print(s2,id(s2))----------{10, 20, 'Python'} 2424308898432
>>> s1.update(s2)
>>> print(s1,id(s1))----------{20, 10, 'Python', 30} 2424308896416
===================================X===========================
Nested or Inner Formulas
-----------------------------------

Imp Points:
--------------------------
=> Set in Set Not Possible
=>Tuple in set Possible (No use bcoz we can't locate by using Indexing )
=>List in set Not Possible ( bcoz list is mutable and allows changes )
=>set in Tuple Possible (boz tuple permits to locate set object by using indexing)
=>Set in list Possible (boz tuple permits to locate set object by using indexing)
-------------------------
Examples:
---------------------------
>>> l1=[10,"Akash",{10,20,30},[23,45,23],"OUCET" ]
>>> print(l1,type(l1))
[10, 'Akash', {10, 20, 30}, [23, 45, 23], 'OUCET'] <class 'list'>
>>> print(l1[0],type(l1[0]))-------------10 <class 'int'>
>>> print(l1[1],type(l1[2]))------------Akash <class 'set'>
>>> print(l1[2],type(l1[2]))----------{10, 20, 30} <class 'set'>
>>> l1[2][0]------------TypeError: 'set' object is not subscriptable
>>> l1[:3]---------------[10, 'Akash', {10, 20, 30}]
>>> l1[2].add(23)
>>> print(l1)------------[10, 'Akash', {10, 20, 30, 23}, [23, 45, 23], 'OUCET']
39
>>> l1[-2][0]------------23
>>> l1[-3][0]--------TypeError: 'set' object is not subscriptable
---------------------
>>> t1=(10,"Akash",{10,20,30},[23,45,23],"OUCET")
>>> print(t1,type(t1))-----------(10, 'Akash', {10, 20, 30}, [23, 45, 23], 'OUCET') <class 'tuple'>
>>> print(t1[2],type(t1[2]))----------{10, 20, 30} <class 'set'>
>>> print(t1[2],type(t1[3]))----------{10, 20, 30} <class 'list'>
------------------------
>>> s1={10,"Akash",(10,20,30),(23,45,23),"OUCET"}
>>> print(s1,type(s1))--------{'OUCET', 'Akash', (23, 45, 23), 10, (10, 20, 30)} <class 'set'>
>>> print(s1[2],type(s1[2]))---TypeError: 'set' object is not subscriptable
>>> s1={10,"Akash",[10,20,30],(23,45,23),"OUCET"}----TypeError: unhashable type: 'list'
-----------------------------------------------------------------------------------------------------
14) pop()
-------------------------------------------------------------------------------------------------------
=>Syntax: setobj.pop()
=>This Function is used for removing any Arbitary Element from setobject.
=>when we call pop() on empty set() then we get KeyError
Examples:
-----------------
>>> s1={10,"Abinash","Python",45.67,True,2+3j}
>>> s1.pop()-------------True
>>> s1.pop()------------10
>>> s1.pop()------------'Abinash'
>>> s1.pop()------------'Python'
>>> s1.pop()---------------(2+3j)
>>> s1.pop()---------------45.67
>>> s1.pop()-------------KeyError: 'pop from an empty set'
>>> set().pop()-----------KeyError: 'pop from an empty set'
------------------------------------------------------------------------------------------------------
==================================
2. frozenset
==================================
=>'frozenset' is one of the pre-defined class and treated as set data type.
=>The purpose of frozenset data type is that To store multiple values of either of same type or
different type or both types with Unique Values in single object."
=>The elements set must organized with curly braces {} and values must separated by comma and
those values can converted into frozenset by using frozenset()

Syntax:- frozensetobj1=frozenset(setobj)
frozensetobj1=frozenset(listobj)
frozensetobj1=frozenset(tupleobj)

=>An object of frozenset does not maintain insertion Order bcoz PVM displays any possibility
of elements of frozenset
=>Since frozenset object does not maintain insertion order, we can't perform Indexing and Slicing
Operations ( frozenset' object is not subscriptable)
=>An object of frozenset belongs to immutable (in the case frozenset' object does not support item
assignment and adding elements also not possible)
-----------------------------------------------------------------------------------------------------------------

40
Note:-The Functionality of frozenset is similar to set but an object of set belongs to both immutable
( in case of item assigment) and mutable (in the case of add()) where as an object frozenset belongs to
immutable.
-----------------------------------------------------------------------------------------------------------------
Examples:
----------------
l1=[10,20,30,40,10]
fs=frozenset(l1)
print(fs,type(fs))----------------frozenset({40, 10, 20, 30}) <class 'frozenset'>
fs.add(100)------------AttributeError: 'frozenset' object has no attribute 'add'
fs[0]=345------------TypeError: 'frozenset' object does not support item assignment
-------------------------------------------------------------------------------------------------------------------
>>> t1=(10,20,30,10,40,23.45,56)
>>> print(t1,type(t1))-------------------(10, 20, 30, 10, 40, 23.45, 56) <class 'tuple'>
>>> fs1=frozenset(t1)
>>> print(fs1,type(fs1))-----------------frozenset({40, 10, 20, 23.45, 56, 30}) <class 'frozenset'>
>>> s1={10,"KVR",34.56,"Python","Java"}
>>> print(s1,type(s1))----------------{34.56, 10, 'KVR', 'Java', 'Python'} <class 'set'>
>>> fs2=frozenset(s1)
>>> print(fs2,type(fs2))------frozenset({34.56, 10, 'KVR', 'Java', 'Python'}) <class 'frozenset'>
>>> fs2[0]-----------------TypeError: 'frozenset' object is not subscriptable
>>> fs2[0:3]---------------TypeError: 'frozenset' object is not subscriptable
>>> fs2[0]=123----------TypeError: 'frozenset' object does not support item assignment
>>> fs2.add(100)------------AttributeError: 'frozenset' object has no attribute 'add'
--------------------------------------------------------------------------------------------------------------
Pre-defined functions in frozenset
-----------------------------------------------------------
1) copy() 2) union() 3) intersection() 4) difference() 5) symmetric_difference()
------------------------------------------------------
Examples:
------------------------------------------------------
>>> s1={10,20,30,40}
>>> s2={15,25,30,40}
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s2)
>>> print(fs1)
frozenset({40, 10, 20, 30})
>>> print(fs2)
frozenset({40, 25, 30, 15})
>>> fs3=fs1.union(fs2)
>>> print(fs3)
frozenset({40, 10, 15, 20, 25, 30})
>>> fs4=fs1.intersection(fs2)
>>> print(fs4)
frozenset({40, 30})
>>> fs5=fs1.difference(fs2)
>>> print(fs5)
frozenset({10, 20})
>>> fs6=fs2.difference(fs1)
>>> print(fs6)
frozenset({25, 15})
>>> fs7=fs2.symmetric_difference(fs1)
41
>>> print(fs7)
frozenset({10, 15, 20, 25})
>>> fs7=fs1.symmetric_difference(fs2)
>>> print(fs7)
frozenset({10, 15, 20, 25})
-------------------------------------------------------------
>>> s1={10,20,30,40}
>>> fs1=frozenset(s1)
>>> fs2=fs1.copy()
>>> print(fs1,id(fs1))-----------------frozenset({40, 10, 20, 30}) 2299638113984
>>> print(fs2,id(fs2))-----------------frozenset({40, 10, 20, 30}) 2299638113984
============================X=================================

The following Pre-defined functions not found in frozenset


1) add() 2) remove() 3) discard() 4) update() 5) pop() 6) clear()

Dict Catagery Data Type (Collection Data Types or Data Structures)


=>The purpose of dict Catagery Data Type is the "To organize the data in the form of
(Key,Value)"
=>To organize the data in the form (key,value), we use a pre-defined class called "dict".
=>"dict" is one of the pre-defined class and treated as dict Catagery Data Type
=>The elements of dict must be organized in the form curly braces { } and (key,value) must
separated by comma.
=>An object of dict maintains insertion Order.
=>On the object of dict, we can't perform Indexing and Slicing Operations.
=>An object of dict belongs to mutable. In otherwords , The Values of Key are belongs to
immutable and Values of Value are belongs to mutable
=>By using dict class , we can create two types of dict objects. They are
a) empty dict
b) non-empty dict
a) An empty dict is one, which does not contain any elements and whose length is 0.
Syntax:- dictobj={}
(or)
dictobj=dict()

=>Syntax for adding (Key,value) to empty dict object

dictobj[Key1]=Value1
dictobj[Key2]=Value2
-----------------------------
dictobj[Key-n]=Value-n

b) A non-empty dict is one, which contains elements and whose length is >0.
Syntax:- dictobj={ Key1:Val1, Key2:Val2.......Key-n:Val-n }
Here Key1,Key2...Key-n are called Keys and They are Unique and they can be either Strs
or Numerics
Here Val1,Val2...val-n are called Values and They may be Unique or duplicate and they
can be either Strs or Numeric
--------------------------------------------------------------------------------------------------------
Examples:
--------------------

42
>>> d1={}
>>> print(d1,type(d1))---------------{} <class 'dict'>
>>> len(d1)---------------0
>>> d2={10:1.2,20:2.5,30:2.5,40:4.5}
>>> print(d2,type(d2))-----------{10: 1.2, 20: 2.5, 30: 2.5, 40: 4.5} <class 'dict'>
>>> len(d2)------------4
-----------------------------------------------------------------------------------------------------------
>>> d3=dict()
>>> print(d3,type(d3), len(d3))-------- {} <class 'dict'> 0
>>> d1={"Rossum":"Python","Ritche":"C", "Gosling":"Java"}
>>> print(d1,type(d1))----{'Rossum': 'Python', 'Ritche': 'C', 'Gosling': 'Java'} <class 'dict'>

>>> d2={10:"Apple",20:"Mango",30:"Kiwi",40:"Sberry"}
>>> print(d2)-----{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'}
-------------------------------------------------------
>>> print(d2[0])--------KeyError: 0
>>> print(d2[10])---------Apple
>>> print(d2[40])--------Sberry
>>> print(d2[400])--------KeyError: 400
-------------------------------------------------------------------
>>> d1={}
>>> print(d1,type(d1),len(d1), id(d1))----{} <class 'dict'> 0 2299637840384
>>> d1[100]="Rossum"
>>> d1[101]="Ritche"
>>> d1[102]="Travis"
>>> d1[103]="MCKinney"
>>> print(d1,type(d1),len(d1), id(d1))----{100: 'Rossum', 101: 'Ritche', 102: 'Travis', 103:

'MCKinney'} <class 'dict'> 4 2299637840384

>>> d1[100]="Guido"
>>> print(d1,type(d1),len(d1), id(d1))-----{100: 'Guido', 101: 'Ritche', 102: 'Travis', 103:

'MCKinney'} <class 'dict'> 4 2299637840384


==============================X================================
==========================================
pre-defined functions in dict data type
=>dict object contains the following pre-defined function to perform Various Operations.
1) clear()
=>Syntax:- dictobj.clear()
=>This function removes all the (key,Value) from dict object
=>When we call clear() upon empty dict object then we get None

Examples:
>>> d1={10:1.2,20:2.3,40:5.6,50:1.2}
>>> print(d1,type(d1), id(d1))------------{10: 1.2, 20: 2.3, 40: 5.6, 50: 1.2} <class 'dict'>
1228171857856
>>> d1.clear()
>>> print(d1,type(d1), id(d1))------------{} <class 'dict'> 1228171857856
>>> print(d1.clear())---------------None
---------------------------------------------------------------------------------------------------

43
2) copy()
=>Syntax: dictobj2=dictobj1.copy()
=>This Function is used copying the content of one dict object into another dict object (
implementation of shalow copy)

Examples:
>>> d1={10:1.2,20:2.3,40:5.6,50:1.2}
>>> print(d1,type(d1), id(d1))-----{10: 1.2, 20: 2.3, 40: 5.6, 50: 1.2} <class 'dict'> 1228176102528
>>> d2=d1.copy()
>>> print(d2,type(d2), id(d2))----{10: 1.2, 20: 2.3, 40: 5.6, 50: 1.2} <class 'dict'> 1228171857856
---------------------------------------------------------------------------------------------------
3) pop()
=>Syntax: dictobj.pop(Key)
=>This Function is used removing (Key,Value) from non-dict object
=>if we call this function on empty dict object we get KeyError
Examples:
>>> d1={10:1.2,20:2.3,40:5.6,50:1.2}
>>> print(d1,type(d1), id(d1))----{10: 1.2, 20: 2.3, 40: 5.6, 50: 1.2} <class 'dict'> 1228176103168
>>> d1.pop(20)---------2.3
>>> print(d1,type(d1), id(d1))------{10: 1.2, 40: 5.6, 50: 1.2} <class 'dict'> 1228176103168
>>> d1.pop(40)-----5.6
>>> print(d1,type(d1), id(d1))---{10: 1.2, 50: 1.2} <class 'dict'> 1228176103168
>>> d1.pop(10)-------1.2
>>> print(d1,type(d1), id(d1))---{50: 1.2} <class 'dict'> 1228176103168
>>> d1.pop(50)------1.2
>>> d1.pop(150)------KeyError: 150
---------------------------------------------------------------------------------------------------
4) popitem()
=>Syntax: dictobj.popitem()
=>This Function is used removing last entry of (Key,Value) from non-dict object
=>if we call this function on empty dict object we get KeyError
Examples:
>>> d1={10:1.2,20:2.3,40:5.6,50:1.2}
>>> print(d1,type(d1), id(d1))--{10: 1.2, 20: 2.3, 40: 5.6, 50: 1.2} <class 'dict'> 1228171857920
>>> d1.popitem()---(50, 1.2)
>>> print(d1,type(d1), id(d1))---{10: 1.2, 20: 2.3, 40: 5.6} <class 'dict'> 1228171857920
>>> d1.popitem()---(40, 5.6)
>>> print(d1,type(d1), id(d1))---{10: 1.2, 20: 2.3} <class 'dict'> 1228171857920
>>> d1.popitem()--(20, 2.3)
>>> print(d1,type(d1), id(d1))--{10: 1.2} <class 'dict'> 1228171857920
>>> d1.popitem()---(10, 1.2)
>>> print(d1,type(d1), id(d1))--{} <class 'dict'> 1228171857920
>>> d1.popitem()----KeyError: 'popitem(): dictionary is empty'
>>> {}.popitem()-----KeyError: 'popitem(): dictionary is empty'
>>> dict().popitem()---KeyError: 'popitem(): dictionary is empty'
---------------------------------------------------------------------------------------------------
5) keys()
=>Syntax: Varname=dictobj.keys()
(OR)
dictobj.keys()
=>This Function is used for obtaining values of Key.

44
Examples:
>>> d1={10:"Python",20:"Data Sci",30:"Django",40:"Java"}
>>> print(d1,type(d1))-----------{10: 'Python', 20: 'Data Sci', 30: 'Django', 40: 'Java'} <class 'dict'>
>>> d1.keys()------------dict_keys([10, 20, 30, 40])
>>> kvs=d1.keys()
>>> print(kvs)--------------dict_keys([10, 20, 30, 40])
>>> for k in kvs:
... print(k)
...
10
20
30
40
>>> for k in d1.keys():
... print(k)
...
10
20
30
40
NOTE:
>>> d1={10:"Python",20:"Data Sci",30:"Django",40:"Java"}
>>> print(d1,type(d1))------------{10: 'Python', 20: 'Data Sci', 30: 'Django', 40: 'Java'} <class 'dict'>
>>> k=d1.keys()
>>> print(k)------------------dict_keys([10, 20, 30, 40])
>>> print(k,type(k))----------dict_keys([10, 20, 30, 40]) <class 'dict_keys'>
>>> l=list(k)
>>> print(l,type(l))--------------[10, 20, 30, 40] <class 'list'>
>>> print(l[0])-------------10
----------------------------OR-----------------------------------
>>> d1={10:"Python",20:"Data Sci",30:"Django",40:"Java"}
>>> print(d1,type(d1))--------{10: 'Python', 20: 'Data Sci', 30: 'Django', 40: 'Java'} <class 'dict'>
>>> list(d1.keys())[0]------------10
---------------------------------------------------------------------------------------------------
6) values()
Syntax: Varname=dictobj.values()
(OR)
dictobj.values()
=>This Function is used for obtaining Values of Value.
Examples:
>>> d1={10:"Python",20:"Data Sci",30:"Django",40:"Java"}
>>> print(d1,type(d1))---------------{10: 'Python', 20: 'Data Sci', 30: 'Django', 40: 'Java'} <class 'dict'>
>>> d1.values()------------dict_values(['Python', 'Data Sci', 'Django', 'Java'])
>>> vs=d1.values()
>>> print(vs)---------------dict_values(['Python', 'Data Sci', 'Django', 'Java'])
>>> for v in vs:
... print(v)
...
Python
Data Sci
Django
Java

45
>>> for v in d1.values():
... print(v)
Python
Data Sci
Django
Java
---------------------------------------------------------------------------------------------------
7) items()
Syntax:- varname=dictobj.items()
(OR)
dictobj.items()
=>This Function is used for obtaing (Key,Value) from dict object in the form of list of tuples.
Examples
>>> d1={10:"Python",20:"Data Sci",30:"Django",40:"Java"}
>>> print(d1,type(d1))----------{10: 'Python', 20: 'Data Sci', 30: 'Django', 40: 'Java'} <class 'dict'>
>>> d1.items()---dict_items([(10, 'Python'), (20, 'Data Sci'), (30, 'Django'), (40, 'Java')])
>>> kv=d1.items()
>>> print(kv)--dict_items([(10, 'Python'), (20, 'Data Sci'), (30, 'Django'), (40, 'Java')])
-------------------------
>>> for x in kv:
... print(x)
...
(10, 'Python')
(20, 'Data Sci')
(30, 'Django')
(40, 'Java')
>>> for k,v in kv:
... print(k,v)
...
10 Python
20 Data Sci
30 Django
40 Java
>>> for k,v in kv:
... print(k,"-->",v)
...
10 --> Python
20 --> Data Sci
30 --> Django
40 --> Java
>>> for k,v in d1.items():
... print(k,"-->",v)
...
10 --> Python
20 --> Data Sci
30 --> Django
40 --> Java
---------------------------------------------------------------------------------------------------
8) update()
Examples:
------------------
>>> d1={10:1.2,20:3.4}

46
>>> d2={30:1.5,40:5.6}
>>> print(d1,type(d1))--------------{10: 1.2, 20: 3.4} <class 'dict'>
>>> print(d2,type(d2))-------------{30: 1.5, 40: 5.6} <class 'dict'>
>>> d1.update(d2)
>>> print(d1,type(d1))---------{10: 1.2, 20: 3.4, 30: 1.5, 40: 5.6} <class 'dict'>
>>> print(d2,type(d2))---------{30: 1.5, 40: 5.6} <class 'dict'>
--------------------------------
>>> d1={10:1.2,20:3.4}
>>> d2={10:6.5,20:7.6}
>>> print(d1,type(d1))-------------{10: 1.2, 20: 3.4} <class 'dict'>
>>> print(d2,type(d2))------------{10: 6.5, 20: 7.6} <class 'dict'>
>>> d1.update(d2)
>>> print(d1,type(d1))--------------{10: 6.5, 20: 7.6} <class 'dict'>
>>> print(d2,type(d2))--------------{10: 6.5, 20: 7.6} <class 'dict'>
----------------------------------------------
>>> d1={10:1.2,20:3.4}
>>> d2={30:1.5,10:15.6}
>>> print(d1,type(d1))------------{10: 1.2, 20: 3.4} <class 'dict'>
>>> print(d2,type(d2))------------{30: 1.5, 10: 15.6} <class 'dict'>
>>> d1.update(d2)
>>> print(d1,type(d1))-----------{10: 15.6, 20: 3.4, 30: 1.5} <class 'dict'>
>>> print(d2,type(d2))---------{30: 1.5, 10: 15.6} <class 'dict'>
---------------------------------------------------------------------------------------------------
9) get()
---------------------------------------------------------------------------------------------------
=>Syntax: Varname=dictobj.get(Key)
(OR)
dictobj.get(Key)
=>This Function is used for finding value of Value by passing Value of Key
=>If Value of Key does not exist then we get None.
Examples:
---------------------
>>> d1={"TS":"HYD","AP":"AMVT","KAR":"BANG","TAMIL":"CHE"}
>>> print(d1)----------{'TS': 'HYD', 'AP': 'AMVT', 'KAR': 'BANG', 'TAMIL': 'CHE'}
>>> d1["TS"]--------'HYD'
>>> d1["TAMIL"]----------'CHE'
>>> d1["AMPT"]---------KeyError: 'AMPT'
>>> d1.get("AP")-----------'AMVT'
>>> d1.get("KAR")-----------'BANG'
>>> d1.get("SRN")--------
>>> print(d1.get("SRN"))------None
----------
NOTE:
----------
We can get Value of Value by passing Key by using the syntax also.

Syntax: varname=dictobj[Key]

=>Here if Value of Key does not Exist then we get KeyError


---------------------------------------------------------------------------------------------------
MISC Examples:
---------------------------------------------------------------------------------------------------

47
>>> d1={10:"Python",20:"Data Sci",30:"Django",40:"Java"}
>>> print(d1,type(d1))--------{10: 'Python', 20: 'Data Sci', 30: 'Django', 40: 'Java'} <class 'dict'>
>>> kvs=d1.items()
>>> print(kvs, type(kvs))-------dict_items([(10, 'Python'), (20, 'Data Sci'), (30, 'Django'), (40, 'Java')])
<class 'dict_items'>
>>> l1=list(kvs)
>>> print(l1,type(l1))---[(10, 'Python'), (20, 'Data Sci'), (30, 'Django'), (40, 'Java')] <class 'list'>
>>> l1[0]------------(10, 'Python')
>>> l1[1]----------(20, 'Data Sci')
>>> l1[2]----------(30, 'Django')
>>> l1[-1]---------(40, 'Java')
--------------------------------------------------
>>> d1={10:"Python",20:"Data Sci",30:"Django",40:"Java"}
>>> print(d1,type(d1))---{10: 'Python', 20: 'Data Sci', 30: 'Django', 40: 'Java'} <class 'dict'>
>>> lst=list(d1.items())
>>> print(lst)------[(10, 'Python'), (20, 'Data Sci'), (30, 'Django'), (40, 'Java')]
------------------------------------------------------------------------------------------------------------------------
Most Useful case:
------------------------------------------------------------------------------------------------------------------------
>>> l1=[(10,"Rizwan"),(20,"Rossum"),(30,"Rajesh"),(40,"Ranjit")]
>>> print(l1,type(l1))------[(10, 'Rizwan'), (20, 'Rossum'), (30, 'Rajesh'), (40, 'Ranjit')] <class 'list'>
>>> d1=dict(l1)
>>> print(d1,type(d1))----{10: 'Rizwan', 20: 'Rossum', 30: 'Rajesh', 40: 'Ranjit'} <class 'dict'>
-----------------------------------------------------------------------------------------------------------------
Most Useful case
> l1=(10,20,30,40)
>>> l2=(1.2,2.3,4.5,1.5)
>>> d1=dict(zip(l1,l2))
>>> print(d1)-------------{10: 1.2, 20: 2.3, 30: 4.5, 40: 1.5}
-----------------------------------
>>> l1=(10,20,30,40)
>>> l2=(1.2,2.3)
>>> d=dict(zip(l1,l2))
>>> print(d,type(d))--------------{10: 1.2, 20: 2.3} <class 'dict'>
-------------------------------------------------------------------
>>> print(d1,type(d1))
{10: ['C', 'CPP'], 20: {'PYTHON': {'Core': 'GUI', 'ADV': 'OOPS'}, 30: 'OUCET'}} <class 'dict'>
>>>
>>> for k,v in d1.items():
... print(k,"--->",v)
...
10 ---> ['C', 'CPP']
20 ---> {'PYTHON': {'Core': 'GUI', 'ADV': 'OOPS'}, 30: 'OUCET'}
>>> len(d1)-----2
>>> d1[20]
{'PYTHON': {'Core': 'GUI', 'ADV': 'OOPS'}, 30: 'OUCET'}
>>> type(d1[20])-----------<class 'dict'>
>>> len(d1[20])------------2
----------------------------------------------------------------------------------------------------------
=======================================
NoneType data type
=======================================
48
=>'NoneType' is one the pre-defined class and treated as None type Data type
=> "None" is keyword acts as value for <class,'NoneType'>
=>The value of 'None' is not False, Space , empty , 0
=>An object of NoneType class can't be created explicitly.
--------------------------------------------------------------------
Examples:
------------------
>>> a=None
>>> print(a,type(a))------------None <class 'NoneType'>
>>> a=NoneType()---------NameError: name 'NoneType' is not defined
>>> l1=[]
>>> print(l1.clear())------------None
>>> s1=set()
>>> print(s1.clear())---------None
>>> d1=dict()
>>> print(d1.clear())-----------None
>>> d1={10:1.2,20:3.4}
>>> print(d1.get(100))---------None
-------------------------------------------------------------------------------------------------------------------
Number of approaches for development of Programs in Python
=>Definition of Program:
=>Set of Optimized Instructions is called Program.
=>Programs are always developed by Language Programmers for solving Real Time
Applications.
=>To solve any Real Time Application, we must write Set of Optimized Instructions and
save those Instructions on Some File Name with an extension .py
(FileName.py------>Considered as Python Program)
=>In Python Programming, we can develop any Program with Approaches.
They are 1. Interactive Mode Approach 2. Batch Mode Approach

1. Interactive Mode Approach


=>In This approach, the programmer can issue one Instruction at a time and gets One
Output at a time.
=>This Approach is more useful to test one Instruction at a time.
=>This Approach is not useful for Developing Code for Big Problems and more over
we are unable to save the instructions.
Examples:
>>> a=10 >>> b=20 >>> c=a+b
>>> print(a)->10 >>> print(b)->20 >>> print(c)->30
Software-> 1)Python Command 2)Python IDLE Shell

2. Batch Mode Approach


=>The Process of defining Group of Instructions under one editor and save those
instructions on some file name with an extension .py
(FileName.py--Source Code) is called Batch Mode Approach
=>This Approach is more useful for solving Big Problems

49
Software: Python IDLE Shell (Will come on the Installation
Python )
Edit Plus (Install Explicitly )
Pycharm
Jupiter NoteBook
Spider
Visual Studio (VS Code)
Google Clab
Atom
sub lime Text

#Program for mul of two numbers


#MulEx.py---File Name
a=float(input("Enter Value a:"))
b=float(input("Enter Value b:"))
c=a*b
print("----------------------")
print("Val of a=",a)
print("Val of b=",b)
print("Mul=",c)
print("----------------------")
--------------------------------------------------------------------------------------------------------=>To
run the Python Program from Windows Command Prompt, we use "python" or "py"
=>Syntax: E:\KVR-PYTHON-11am\Batch-Mode>python MulEx.py
==================================x===========================
#program for computing sum of two numbers
a=float(input("Enter First value:"))
b=float(input("Enter Second value:"))
c=a+b
print("========Result========")
print("val of a=",a)
print("val of b=",b)
print("Sum=",c)
print("=====================")

Display the Result of Python Program on the console


50
=>To display the result of Python Program on the console, we use a pre-defined
Function called print().
=>print() is one of the pre-defined Function used for displaying the result of Python
Program on the console
=>print() contains the following Syntaxes
Syntax-1:
=>Syntax: print(value) (OR) print(Variable Name) (OR) print(Val1,val2....val-n)
(OR) print(var1,var2.....var-n)
=>This Syntax used for Displaying Only Values or Values of variables.
Examples:
>>> sno=10 >>> sname="Rossum" >>> sub="Python" >>> print(sno)->10
>>> print(sname)->Rossum >>> print(sub)->Python
>>> print(sno,sname,sub)->10 Rossum Python
>>> print(100,200,300)->100 200 300
--------------------------------------------------------------------------------------------------------
Syntax-2
Syntax: print(Message) (OR) print(Message1,Message2,....,Message-n)
=>This Syntax display only Messages.
Examples:
>>> print("hello Python world")->hello Python world
>>> print('hello Python world')->hello Python world

Syntax-3
Syntax: print(Values cum Messages) (OR) print(Messages cum Values)
=>This Syntax displays the values cum messages or Messages cum Values
Examples:
>>> a=10 >>> print(a)->10 >>> print("Value of a=",a)->Value of a= 10
>>> print(a,' is the value of a')->10 is the value of a
>>> a=10 >>> b=20 >>> c=a+b
>>> print("sum=",c)->sum= 30
>>> print(c," is the sum")->30 is the sum
>>> print("sum of ",a," and ",b,"=",c)->sum of 10 and 20 = 30

>>> a=10 >>> b=20 >>> c=30 >>> d=a+b+c


>>> print("Sum of ",a,",",b," and ",c,"=",d)->Sum of 10 , 20 and 30 = 60

Syntax-4
Syntax: print (Values cum Messages with format ()) (OR)print(Messages cum Values
with format() )

Examples:
>>> a=10 >>> b=20 >>> c=a+b
>>> print("Sum={}".format(c))->Sum=30
>>> print("{} is the sum".format(c))->30 is the sum
>>> print("sum of ",a," and ",b,"=",c)->sum of 10 and 20 = 30
51
>>> print("sum of {} and {}={}".format(a,b,c))->sum of 10 and 20=30
>>> sno=10 >>> sname="Rossum"
>>> print(" '{}' is a student and roll number is {}".format(sname,sno))--- 'Rossum' is a
student
and roll number is 10
Syntax-5
Syntax: print(Values cum Messages with format specifiers) (OR)
print(Messages cum Values with format specifiers )

Examples:
>>> a=10 >>> b=20 >>> c=a+b
>>> print("Sum=%d" %c)->Sum=30
>>> print("%d is the sum" %c)->30 is the sum
>>> print("Sum of %d and %d = %d" %(a,b,c))->Sum of 10 and 20 = 30
>>> sno=10 >>> sname="Elite Elderson" >>> marks=33.33
>>> print("My Number is %d and name is '%s' &Marks=%f" %(sno,sname,marks))
My Number is 10 and name is 'Elite Elderson' and Marks=33.330000
>>> print("My Number is %d and name is '%s' and Marks=%0.2f" %
(sno,sname,marks))
My Number is 10 and name is 'Elite Elderson' and Marks=33.33
>>> print("My Number is %d and name is '%s' and Marks=%0.1f" %
(sno,sname,marks))
My Number is 10 and name is 'Elite Elderson' and Marks=33.3
-----------------
>>> a=1.2 >>> b=20 >>> c=a+b
>>> print("sum of %f and %f=%f".format(a,b,c))----sum of %f and %f=%f
>>> print("sum of %f and %f=%f" %(a,b,c) )----sum of 1.200000 and
20.000000=21.200000
>>> print("sum of %0.2f and %0.2f=%0.3f" %(a,b,c) )--sum of 1.20 and 20.00=21.200
>>> t=(10,"Mr.Crazy",33.33,"Sathish")
>>> print(t)------------(10, 'Mr.Crazy', 33.33, 'Sathish')
>>> print("content of t=",t)--------content of t= (10, 'Mr.Crazy', 33.33, 'Sathish')
>>> print("content of t={}".format(t))----content of t=(10, 'Mr.Crazy', 33.33, 'Sathish')
>>> print("content of t=%s" %str(t))---content of t=(10, 'Mr.Crazy', 33.33, 'Sathish')

Syntax-6:
Syntax: print(Value cum Message, end=" ")
=>This syntax displays the data in same Line

Examples:
>>> lst=[10,20,30,40,50,60]
>>> for val in lst:
... print(val)
...
52
10
20
30
40
50
60
>>> for val in lst:
... print(val,end=" ")-------- 10 20 30 40 50 60
>>> for val in lst:
... print(val,end="-->")----- 10-->20-->30-->40-->50-->60-->
>>> lst=[10,20,30,40,50,60]
>>> for val in lst:
... print("{}".format(val), end="\t") 10 20 30 40 50 60 >>>
----------------------
>>> lst=[10,20,30,40,50,60]
>>> for val in lst:
... print("%d" %val, end=" ")->10 20 30 40 50 60
------------------------------------------------------------------------
Reading the data or input from Key Board
=>To read the data from Keyboard, we use Two pre-defined Functions.
They are 1. input() 2. input(Message)
1) input()
=>This Function is used for Reading any type of data from Key board in the form of str
type only.
=>Syntax:- varname=input()
=>Here input() reads the value in the form str and place that value in varname.
=>The value of str can type casted to any other types by using Type Casting functions.

Examples
#Program for accepting two integer values and multiply them
#MulExample3.py
print("Enter two Values:")
a=float( input() )
b=float( input() )
#Multiply them
c=a*b
print("Mul({},{})={}".format(a,b,c))

2) input(Message)
=>This Function is used for Reading any type of data from Key board in the form of str
type only and with Function additionally we can provide User-Prompting Message.

=>Syntax: varname=input(Message)

=>here Message Represents User-Prompting Message.


53
=>Here input(Message) reads the value in the form str and place that value in varname
by giving User-Prompting Message.
=>The value of str can type casted to any other types by using Type Casting functions.

Operators and Expressions in python


=>An Operator is a symbol which is used to perform certain operations.
=>If any operator connected with two or more Objects / Variables then is it called
Expression.
=>An Expression is a collection of objects or variables connected with Operators.
=>In python Programming, we have 7 types of Operators. They are

1. Arithmetic
Operators
2. Assignment
Operator
3. Relational
Operators
4. Logical Operators
5. Bitwise Operators
(Most Imp)
6. Membership
Operators
a) in
b) not in
7. Identity Operators
a) is
b) is not

1. Arithmetic Operators
=>The purpose of Arithmetic Operators is that "To Perform Arithmetic Operations
such as addition, subtraction...etc"
=>If Two or More Objects or Variables connected with Arithmetic Operators then it is
called Arithmetic Expressions.
=>In Python programming, we have 7 types of Arithmetic Operators. They are given
in the following Table.

S SY MEANING EXAMPLE
S
a=10
b=3
1. + Addition print(a+b)
------
13
2. - Subtract print(a-
54
b)----
----7
3. * Multiplicat print(a*b)
ion -------
30
4. / Division(Fl print(a/
oat) b)----
--
3.333
3333
3
5. // Floor print(a//
Divisi b)----
on(Int 3
)
6. % Modulo print(a
Divisi %b)--
on --1
7. ** Exponenti print(a**b
ation )---
100
2. Assignment Operator
=>The purpose of assignment operator is that " To assign or transfer Right Hand Side
(RHS) Value / Expression Value to the Left Hand Side (LHS) Variable "
=>The Symbol for Assignment Operator is single equal to ( = ).
=>In Python Programming, we can use Assignment Operator in two ways.
1. Single Line Assignment 2. Multi Line Assignment

1. Single Line Assignment:


=>Syntax: LHS Varname= RHS Value (or) LHS Varname= RHS Expression

=>With Single Line Assignment at a time we can assign one RHS Value / Expression to
the single LHS Variable Name.
Examples:
>>> a=10 >>> b=20 >>> c=a+b >>> print(a,b,c)->10 20 30

2. Multi Line Assignment:

=>Syntax: Var1,Var2.....Var-n= Val1,Val2....Val-n (or)


Var1,Var2.....Var-n= Expr1,Expr2...Expr-n

Here The values of Val1, Val2...Val-n are assigned to Var1,Var2...Var-n Respectively.


Here The values of Expr1, Expr2...Expr-n are assigned to Var1,Var2...Var-n Respectively.

Examples:
55
>>> a,b=10,20 >>> print(a,b)->10 20 >>> c,d,e=a+b,a-b,a*b
>>> print(c,d,e)->30 -10 200
============================================================
3.Relational Operators
=>The purpose of Relational Operators is that "To Compare Two or More Values "
=>If two or more Variables or Objects connected with Relational Operator then it is
Relational Expression.
=>The Result of Relational Expression is either True or False.
=>The Relational Expression is called Test Condition
=>In Python Program, The Relational Operators are classified into 6 types. They are
given in the following table

SLNO SYMBOL MEANING EXAMPLE


1. > Greater than print(10>20)------False
print(10>2)--------True
2. < Less Than print(10<20)------True
print(10<5)--------False
3. == Equality print(10==10)----True
print(10==5)------False
4. != Not Equal to print(10!=20)----True
print(10!=10)----False
5. >= Greater Than print(10>=5)-----True
or Equal to print(10>=11)----False
6. <= Less Than print(-30<=-34)----False
or Equal to print(-15>=-16)---True
4. Logical Operators
=>The purpose of Logical Operators is that "To Connect Two or more Relational
Expressions".
=>If two or more Relational Expressions connected with Logical Operators then it is
called Logical Expression or Compound Conditions (Multiple condition).
=>The result of Logical Expression or Compound Conditions is either True or False.
=>In Python Programming, we have three types of Logical Operators. They are given in
the following Table.

SLN SYMBOL MEANING


O
1 and Physical
ANDing
2. or Physical
ORing
3. not

1) and :

56
=>The Functionality of "and" operator is described in the following Truth Table.

Rel Expr1 RelExpr2 RelExpr1 and Rel Expr2


False False False
False True False
True False False
True True True
Examples:
>>> print(100>20 and 20>4)->True
>>> print(100>200 and 20>4)->False-> Short Circuit Evaluation
>>> print(-100>200 and 20>4 and 10>2)->False-> Short Circuit Evaluation
=>Short Circuit Evaluation (or) Lazy Evaluation in the case of "and"
In the case of "and" operator, if First Relational Expression result is False Then PVM
will not evaluate rest of the Relational Expression and total Logical Expression result
will be considered as False. This process is called Short Circuit Evaluation (or) Lazy
Evaluation of "and" operator.
2) or :
=>The Functionality of "or" operator is described in the following Truth Table.

Rel Expr1 RelExpr2 RelExpr1 or Rel


Expr2
False False False
True False True
False True True
True True True
Examples:
>>> print(10>2 or 10>4)->True->Short Circuit Evaluation
>>> print(10<2 or 20>3 or 5>50)->True->Short Circuit Evaluation
>>> print(10>2 or 20==3 or 5!=50)->True->Short Circuit Evaluation
>>> print(10==2 or 20==3 or 5>=50)->False

=>Short Circuit Evaluation (or) Lazy Evaluation in the case of "or"


In the case of "or" operator, if First Relational Expression result is True Then PvM will
not evaluate rest of the Relational Expressions and total Logical Expression result will
be considered as True. This process is called Short Circuit Evaluation (or) Lazy
Evaluation of "or" operator.
3) not operator:
=>The Functionality of "not" operator is described in the following Truth Table.

Rel Expr1 not RelExpr1


False True
True False
Examples:
>>> a=10 >>> b=20 >>> a==b->False >>> not(a==b)->True
57
>>> print( not (10==2 or 20==3 or 5>=50))->True
>>> a=True >>> not a->False .>> not False->True
Special Examples:
>>> 100>20 and 100>40->True >>> 100>20 or 100>40->True
>>> 100 and -100 -100
>>> 100 and 0 0
>>> -100 and -225 -225
>>> 0 and 100 0
>>> 100 and -1234567 -1234567
>>> 100 and 0 0
>>> 0 and 345 0
>>> 0 and 0 0
>>> 100 or 200 100
>>> -100 or -223 -100
>>> 0 or -223 -223
>>> 0 or 0 0
>>> not (0 or 0) True
>>> 100 and -100 -100
>>> 0 and 10 0
>>> 10 and 20 20
>>> 0 and -100 0
>>> 100 and 0 0
>>> 100 and 200 and -100 -100
>>> 100 and 200 and 0 0
>>> 100 and -200 and 0 and 234 0
>>> "KVR" and "PYTHON" 'PYTHON'
>>> "KVR" and 0 0
>>> "KVR" and "Python" and True True
>>> 100 or 200 100
>>> 100 or 0 100
>>> 0 or 200 200
>>> 0 or 300 or 300 or 100 300
>>> "KVR" or "PYTHON" 'KVR'
>>> 10 or 20 and 30 or 30 and 450 10
>>> 10 and 20 or 300 and 450 and 0 or 23 20
>>> 100 and "or" 'or'
>>> "and" and "or" 'or'
>>> "and" or "or" 'and'

5. Bitwise Operators (Most Imp)


=>Bitwise Operators are Performing the Operation on Integer Data in the form Binary
Bits.
=>Bitwise Operators are applicable on Integer Data but not floating point values bcoz
floating values does not have certainty.

58
=>In Bitwise Operators, First Given Integer Data Converted into Binary data and they
starts
performing operation Bit by Bit and hence they named Bitwise Operators.
=>In Python Programming, we have 6 types of Bitwise Operators. They are
1. Bitwise Left Shift ( << )
Operator
2. Bitwise Right Shift ( >> )
Operator
3. Bitwise AND Operator (&)
4. Bitwise OR Operator (|)
5. Bitwise Complement (~)
Operator
6. Bitwise XOR Operator (^)
1. Bitwise Left Shift Operator ( << ):
Syntax:- varname = Given Number << No. of Bits
=>This Operator Shits or Fipping-off No. of Bits of Given Number from Left Side and add
Number of Zeros (depends on No. of Bits) at Right Side.
Examples:
>>> print(10<<3)->80 >>> print(4<<4)->64
>>> print(8<<3)->64 >>> print(2<<3)->16
>>> print(5<<2)->20

2. Bitwise Right Shift Operator ( >> ):


Syntax: - varname = Given Number >> No. of Bits
=>This Operator Shits or Flipping-off No. of Bits of Given Number from Right Side and
add Number of Zeros (depends on No. of Bits) at Left Side.
Examples:
>>> print(10>>3)->1 >>> print(10>>2)->2 >>> print(12>>2)->3
>>> print(100>>4)->6
3. Bitwise AND Operator ( & )
=>Syntax:- Varname = Var1 & Var2
=>The Functionality of Bitwise AND Operator ( & ) is expressed in the following Truth
table.
Var Var2 Var1 &
1 Var2
0 1 0
1 0 0
0 0 0
1 1 1
Examples:
>>>a=10 ->1010
>>>b= 4 -> 0100
>>>c=a&b -> 0000
>>>print(c)->0 >>> print(7&4)->4 >>> print(6&10)->2

59
>>> 10 & 20->0 >>> 10 and 20->20

4. Bitwise OR Operator ( | )
-=>Syntax:- Varname = Var1 | Var2
=>The Functionality of Bitwise OR Operator ( | ) is expressed in the following Truth
table.
Var1 Var2 Var1 |
Var2
0 1 1
1 0 1
0 0 0
1 1 1

Examples:
>>>a=4->0100 >>>b=3->0011 >>>c=a|b->0111
>>>print(c)->7>>> print(10|15)->15 >>> print(7|3)->7 >>> print(2|5)->7

5. Bitwise Complement Operator ( ~ )


=>Bitwise Complement Operator ( ~ ) is used obtaining complement of a Given
Number.
=>complement of a Given Number= - (Given Number+1)
=>Internally, Bitwise Complement Operator invert the bits (Nothing But 1 becomes 0
and 0 becomes 1--- called 1 's complement)
Examples:
>>> a=17 >>> ~a->-18
>>> a=-98 >>> ~a-> 97
>>> n=200 >>> ~n-> -201
>>> n=304 >>> ~n-> -305
Working Examples:
4-> 0100 ~4-> -(0100+1) 0100+0001=-(0101)

10->1010 ~10-> -(1010+1) 1010+0001=-(1011)


OR 10-> 1010 ~10-> 0101 (Inverting the bits)
11-> 1011 1's complement------------ 0100 (Inverting the bits)
2's complement----1's complement of 11 + 1=0100+0001=0101
4->0100 ~4->1011
What is -5 ( 2's complement 5=1 's complement of 5+1)
5-> 0101
1's complement=1010
2'2complement= 1's complement +1=1010 +1=>1010+0001=1011

6. Bitwise XOR Operator ( ^ )


=>Syntax:- Varname = Var1 ^ Var2
=>The Functionality of Bitwise XOR Operator ( ^ ) is expressed in the following Truth
table.
60
Var Var2 Var1 ^
1 Var2
0 1 1
1 0 1
0 0 0
1 1 0
Examples:
>>> a=3 >>> b=4 >>> c=a^b >>> print(c)->7
>>> print(10^15)->5 >>> print(4^6)->2
Special Case:
>>>s1={10,20,30,40} >>>s2={10,15,25} >>>s3=s1.union(s2)
>>> print(s3)->{20, 40, 25, 10, 30, 15}
>>> s4=s1|s2 # Bitwise OR
>>> print(s4,type(s4))->{20, 40, 25, 10, 30, 15} <class 'set'>
-------------------------------------
>>>s1={10,20,30,40} >>>s2={10,15,25} >>> s3=s1.intersection(s2)
>>> print(s3)->{10} >>> s4=s1&s2 # Bitwise AND
>>> print(s4,type(s4))->{10} <class 'set'>
---------------------------------------------
>>> s1={10,20,30,40} >>> s2={10,15,25} >>> s3=s1.difference(s2)
>>> print(s3)->{40, 20, 30} >>> s4=s1-s2 >>> print(s4)->{40, 20, 30}
>>> s5=s2-s1 >>> print(s5)->{25, 15}
---------------------------------------------------------------
>>> s1={10,20,30,40} >>> s2={10,15,25}
>>> s3=s1.symmetric_difference(s2) >>> print(s3)->{40, 15, 20, 25, 30}
>>> s4=s1^s2 # Bitwise XOR
>>> print(s4,type(s4))->{40, 15, 20, 25, 30} <class 'set'>
Special Examples (Swap two numbers)
>>>a=3 >>>b=4 >>>print(a,b)->3 4
>>>a=a^b >>>b=a^b >>>a=a^b >>>print(a,b)-> 4 3

6.Membership Operators
=>The purpose of Membership Operators is that "To Check the existence of specific
value in Iterable object".
=>An Iterable Object is one which contains Two or More Number of values
=>Sequece Types (str,bytes,bytearray,range) , List (list, tuple) Types , set (set ,
frozenset) Types , and dict type(dict) are comes under Iterable object.
=>In Python Programming, we have two type of Membership Operators.
They are 1) in 2) not in
1) in
Syntax: Value in Iterable Object
=>"in" operator returns True provided "Value" present in Iterable Object
=>"in" operator returns False provided "Value" present not in Iterable Object
2) not in
Syntax: Value not in Iterable Object
61
=>"not in" operator returns True provided "Value" not present in Iterable Object
=>"not in" operator returns False provided "Value" present in Iterable Object
Examples:
>>> s="PYTHON"
>>> s="PYTHON"
>>> "P" in s-----True
>>> "O" in s---True
>>> "O" not in s----False
>>> "k" not in s---True
>>> "k" in s---False
>>> "p" in s---False
>>> "p" not in s--True
>>> not ("p" not in s)--False
>>> "PYT" in s -True
>>> "PYTK" in s--False
>>> "PYTK" not in s-True
>>> "PON" in s-False
>>> "PYN" in s-False
>>> "PYN" not in s-True
>>> "NOH" in sFalse
>>> "HON" not in sFalse
>>> "NOH" in sFalse
>>> "OTP" in sFalse
>>> "OTP" not in sTrue
>>> "NOH" in s[::-1]True
>>> "OTP" not in s[::-2]True
>>> s[::-2]'NHY'
>>> s in sTrue
>>> s in s[::-1]False
>>> s="MADAM"
>>> s in s[::-1]True
----------------------------
>>> s="MADAM" >>> s not in s[::-1][::]False
---------------------------
>>> lst=[10,"Rossum",True,45,2+3j] >>> print(lst)
[10, 'Rossum', True, 45, (2+3j)]
>>> 10 in lst True >>> True in lst True
>>> False not in lst True >>> False in lst False
--------------------------------
>>> lst=[10,"Rossum",True,45,2+3j] >>> print(lst)
[10, 'Rossum', True, 45, (2+3j)]
>>> "sum" in lst False >>> "sum" in lst[1] True
>>> lst[1] in lst[-4][::] True
>>> lst[1][::-2] not in lst[-4][::-2]->False
-------------------------------
62
>>> lst=[10,"Rossum",True,45,2+3j]
>>> lst[-1].real in lst[-1]->TypeError: argument of type 'complex' is not iterable

7.Identity Operators (Python Command Prompt)


=>The purpose of Identity Operators is that "To Check the Memory Address of Two
Objects".
=>In Python Programming, we have two types of Identity Operators.
They are 1. is 2. is not
1) is
Syntax:- object1 is object2
=>"is" opetrator Returns True provided Memory address of Object1 and Object2 are
SAME
=>"is" opetrator Returns False provided Memory address of Object1 and Object2 are
DIFFERENT
2) is not
Syntax:- object1 is not object2
=>"is not" operator Returns True provided Memory address of Object1 and Object2 are
DIFFERENT
=>"is" opetrator Returns False provided Memory address of Object1 and Object2 are
SAME
Examples:
>>> a=None >>> b=None >>> print(a,id(a))->None 140709648996344
>>> print(b,id(b))->None 140709648996344
>>> a is b->True >>> a is not b->False
-------------------------------------------------------------
>>> d1={10:"Apple",20:"Mango",30:"CApple"}
>>> d2={10:"Apple",20:"Mango",30:"CApple"}
>>> print(d1,id(d1))->{10: 'Apple', 20: 'Mango', 30: 'CApple'} 1938668998592
>>> print(d2,id(d2))->{10: 'Apple', 20: 'Mango', 30: 'CApple'} 1938668998656
>>> d1 is d2->False >>> d1 is not d2->True
-------------------------------------------------------------
>>> s1={10,20,30,40} >>> s2={10,20,30,40}
>>> print(s1,id(s1))->{40, 10, 20, 30} 1938669202432
>>> print(s2,id(s2))->{40, 10, 20, 30} 1938673175904
>>> s1 is s2->False >>> s1 is not s2->True
>>> fs1=frozenset(s1) >>> fs2=frozenset(s1)
>>> print(fs1,id(fs1))->frozenset({40, 10, 20, 30}) 1938673176352
>>> print(fs2,id(fs2))->frozenset({40, 10, 20, 30}) 1938673177696
>>> fs1 is fs2->False
>>> fs1 is not fs2->True
-------------------------------------------------------------
>>> t1=(10,20,30) >>> t2=(10,20,30)
>>> print(t1,id(t1))->(10, 20, 30) 1938669461184
>>> print(t2,id(t2))-.>(10, 20, 30) 1938673242496
>>> t1 is t2->False
63
>>> t1 is not t2->True
>>> l1=[10,"Python","R"] >>> l2=[10,"Python","R"]
>>> print(l1,id(l1))->[10, 'Python', 'R'] 1938673238208
>>> print(l2,id(l2))->[10, 'Python', 'R'] 1938669045952
>>> l1 is l2->False >>> l1 is not l2->True
>>> r1=range(10) >>> r2=range(10)
>>> print(r1,id(r1))->range(0, 10) 1938669658224
>>> print(r2,id(r2))->range(0, 10) 1938669663312
>>> r1 is r2->False >>> r1 is not r2->True
>>> b1=bytes([10,20,30]) >>> b2=bytes([10,20,30])
>>> print(b1,id(b1))->b'\n\x14\x1e' 1938669663408
>>> print(b2,id(b2))->b'\n\x14\x1e' 1938669663456
>>> b1 is b2->False >>> b1 is not b2->rue
>>> ba1=bytearray((10,20,123)) >>> ba2=bytearray((10,20,123))
>>> print(ba1,id(ba1))->bytearray(b'\n\x14{') 1938673243440
>>> print(ba2,id(ba2))->bytearray(b'\n\x14{') 1938673243632
>>> ba1 is ba2->False
>>> ba1 is not ba2->True
MOST IMP
>>> s1="PYTHON" >>> s2="PYTHON"
>>> print(s1,id(s1))->PYTHON 1938673243696
>>> print(s2,id(s2))->PYTHON 1938673243696
>>> s1 is s2->True >>> s1 is not s2->False
>>> s1="INDIA" >>> s2="INDIA"
>>> s1 is s2->True >>> s1 is not s2->False
>>> s1="INDIA" >>> s2="INDia"
>>> s1 is s2->False >>> s1 is not s2->True
>>> a=2+3j
>>> b=2+3j
>>> print(a,id(a))->(2+3j) 1938668707664
>>> print(b,id(b))->(2+3j) 1938668707696
>>> a is b->False >>> a is not b->True
>>> a=True >>> b=True
>>> print(a,id(a))->True 140709648943976
>>> print(b,id(b))->True 140709648943976
>>> a is b->True >>> a is not b->False
>>> a=1.2 >>> b=1.2
>>> print(a,id(a))->1.2 1938668708560
>>> print(b,id(b))->1.2 1938668708144
>>> a is b->False >>> a is not b->True
------------------------------------------------------------------
>>> a=10 >>> b=10 >>> print(a,id(a)) 10 1938667667984
>>> print(b,id(b)) 10 1938667667984
>>> a is b True >>> a is not b False
>>> a=256 >>> b=256 >>> print(a,id(a)) 256 1938667675856
64
>>> print(b,id(b)) 256 1938667675856
>>> a is b True >>> a is not b False
>>> a=300 >>> b=300 >>> print(a,id(a)) 300 1938668707664
>>> print(b,id(b)) 300 1938668706064
>>> a is b False >>> a is not b True
>>> a=257 >>> b=257 >>> print(a,id(a)) 257 1938668711440
>>> print(b,id(b)) 257 1938668707664
>>> a is b False >>> a is not b True
>>> a=0 >>> b=0 >>> print(a,id(a)) 0 1938667667664
>>> print(b,id(b)) 0 1938667667664
>>> a is b True >>> a is not b False
>>> a=-4 >>> b=-4 >>> print(a,id(a)) -4 1938667667536
>>> print(b,id(b)) -4 1938667667536
>>> a is b True >>> a is not b False
>>> a=-1 >>> b=-1 >>> print(a,id(a)) -1 1938667667632
>>> print(b,id(b)) -1 1938667667632
>>> a is b True >>> a is not b False
>>> a=-5 >>> b=-5 >>> print(a,id(a)) -5 1938667667504
>>> print(b,id(b)) -5 1938667667504
>>> a is b True >>> a is not b False
>>> a=-6 >>> b=-6 >>> print(a,id(a)) -6 1938668707664
>>> print(b,id(b)) -6 1938668711440
>>> a is b False >>> a is not b True
>>> a,b=300,300 >>> print(a,id(a)) 300 1938668707696
>>> print(b,id(b)) 300 1938668707696
>>> a is b True >>> a is not b False
>>> a,b=-256,-256 >>> print(a,id(a)) -256 1938668706064
>>> print(b,id(b)) -256 1938668706064
>>> a is b True >>> a is not b False
>>> l1,l2=[10,"KVR"],[10,"KVR"] >>> print(l1,id(l1))
[10, 'KVR'] 1938669059648 >>> print(l2,id(l2))
[10, 'KVR'] 1938673238272
>>> l1 is l2 False >>> l1 is not l2 True
-----------------------------------------------------------------------------------------------------
Python Ternary Operator
=>The name of Python Ternary Operator is " if else Operator "
Syntax:- varname= Expr1 if Test Cond else Expr2
Explanation:
=>Here "if" and " else " are called Keywords
=>The Execution Process of if..else operator (Python Ternary Operator) is that" if the
Test Cond result is True then PVM executes Expr1 and whose Result assigned to
Varname. If the Result of Test Cond is False PVM executes Expr2 and whose Result
assigned to Varname".

=============================================
65
Flow Control Statements in Python
Index
=>Purpose of Flow Control Statements in Python
=>Types of Control Statements in Python

I) Conditional or Selection or Branching Statements


1. Simple if statement
2. if..else statement
3. if..elif..else statement
4. match case statement (Python 3.10 Version)
=>Programming Examples
II) Looping or Iterating or Repetitive Statements
1. while loop or while..else loop
2. for loop or for..else loop
=>Programming Examples
III) Transfer Flow Control Statements
1. break
2. continue
3. pass
=>Programming Examples
=>Inner or Nested Loops
a) while loop in while Loop
b) for loop in for loop
c) while loop in for loop
d) for loop in while loop
=>Programming Examples
Flow Control Statements in Python
=>The Purpose of Flow Control Statements in Python is that "To Perform Certain
Operation Either ONCE (True--X-Operation and False--Y-Operation) OR Repeatedly for
finite number of Times Until Condition Becomes False".
=>In Python Programming, Flow Control Statements in Python are classified into 3
types. They are
1. Conditional or Selection or Branching Statements
2. Looping or Iterating or Repetitive Statements
3. Transfer Flow Control Statements
1. Conditional or Selection or Branching Statements
=>The purpose Conditional or Selection or Branching Statements is that " To perform
Certain Operation Only Once depends on Condition Evaluation".
=>The purpose Conditional or Selection or Branching Statements is that "To Perform
X-Operation Only once when the condition is True or To Perform Y-Operation Only
once when the condition is False.".
=>In Python programming, Conditional or Selection or Branching Statements are
classified into 4 types. They are
1. Simple if statement
66
2. if..else statement
3. if..elif..else statement
4. match case statement (Python 3.10 Version Onwards)
--------------------------------------------------------------------------------------------------------
4. match .. case statement (Python 3.10)
==========================================
=>It is one of new Feature in Python 3.10
=>This features is also known as Multi way decision making statement.
=>It is always recommended to handling Pre-designed Conditions.
=>Syntax:
match (Choice Expression):
case label1:
block of statements-I
case label2:
block of statements-II
--------------------------------------
--------------------------------------
case label-n:
block of statements-n
case _ : # default case block
default block of statements
--------------------------------------------------
--------------------------------------------------
Other statements in Program
--------------------------------------------------
Explanation:
1) here 'match' and 'case' are the keywords
2) here 'Choice expression' can be any data type value except float.
3) here the value of choice expression is comparing with case label1 . If it is True then
execute Block of statements-I and also execute other statements in Program. Choice
expression is not matching with case label1 then it compares with case label2 and if it
matches then execute Block of statements-II and also execute other statements in
Program and so on.
4) In general if the value of choice expression is matching with any case label then PVM
executes corresponding block of statements and also executes Other statements in the
program.
5) if value of choice expression is not matching with any case labels then PVM executes
block of statements written under default case block and also executes Other
statements in the program.
6) Writting default case label is optional.
7) If we write default case label then we must write it at last otherwise we get
SyntaxError.

#matchcaseex4.py
67
wkd=input("Enter a week name:")
match(wkd.lower()[0:3]):
case "mon"| "tue" | "wed"|"thu"|"fri":
print("{} is working day".format(wkd))
case "sat":
print("{} is week end--underground action plans".format(wkd))
case "sun":
print("{} is holiday and implementing UG Plans".format(wkd))
case _:
print("{} is not a week day".format(wkd))
Looping or Iterating or Repetitive Statements
=>The purpose of Looping statements is that "To perform Certain Operation
Repeatedly for finite number of times until Test Cond Becomes False."
=>In Python Programming, we have 2 types of Looping statements. They are
1. while loop (OR) while ... else loop
2. for loop (OR) for.... else loop
=>At the time of dealing with looping statements, Programmer must ensure there must
3 parts. They are
1. Initialization Part (From Where to Start)
2. Conditional Part (Up to How Many times to repeat
3. Updation Part ( Incrmentation or decrementation )
2. for loop or for ...else loop
Syntax1:-for varname in Iterable_object:
Indentation block of stmts
Other statements in Program
Syntax2:-for varname in Iterable_object:
Indentation block of stmts
else:
else block of statements
Other statements in Program
Explanation:
=>Here 'for' and 'else' are keywords
=>Here Iterable_object can be Sequence(bytes,bytearray,range,str),
list(list,tuple),set(set,frozenset) and dict.
=>The execution process of for loop is that " Each of Element of Iterable_object selected,
placed in varname and executes Indentation block of statements".This Process will be
repeated until all elements of Iterable_object completed.
=>After execution of Indentation block of statements, PVM executes else block of
statements which are written under else block and later PVM executes Other
statements in Program.
=>Writing else block is optional.

break statement
68
=>break is a key word
=>The purpose of break statement is that "To terminate the execution of loop logically
when certain condition is satisfied and PVM control comes of corresponding loop and
executes other statements in the program".
=>when break statement takes place inside for loop or while loop then PVM will not
execute corresponding else block (bcoz loop is not becoming False) but it executes
other statements in the program
=>Syntax1: for varname in Iterable_object:
if (test cond):
break
=>Syntax2: while(Test Cond-1):
if (test cond-2):
break
Example :
#To print Pyth from the word Python without index & slice operation:
s="Python"
print("For Loop")
for i in s:
if(i=="o"):
break
else:
print(i,end="")
k=0
print("\nWhile Loop")
while(k<len(s)):
if(s[k]=="o"):
break
else:
print(s[k],end="")
k=k+1

continue statement
=>continue is a keyword
=>continue statement is used for making the PVM to go to the top of the loop without
executing the following statements which are written after continue statement for that
current Iteration only.
=>continue statement to be used always inside of loops.
=>when we use continue statement inside of loop then else part of corresponding loop
also executes provided loop condition becomes false.
=>Syntax:- for varname in Iterable-object:
if ( Test Cond):
continue
statement-1 # written after continue statement
statement-2
statement-n

69
=>Syntax:- while (Test Cond):
if ( Test Cond):
continue
statement-1 # written after continue statement
statement-2
statement-n
Inner or Nested Loops
=>The Process of Defining One Loop in another Loop is called Inner or Nested Loop
=>The Execution Process of Inner or Nested Loop is that "For Every Value of Outer
Loop, inner Loop
process repeats Multiple Finite number of times until Test Cond becomes False".
=>We can define Inner or Nested Loops in Four Ways. They are
Syntax-1: for loop in for loop
for varname1 in Iterable_object:
for varname2 in Iterable_object:
-----------------------
-----------------------
else:
---------------------------
else:
-----------------------------------

Syntax-2: while loop in while loop


while(Test Cond1):
-----------------------------
-----------------------------
while (Test Cond2):
--------------------------
--------------------------
else:
-------------------
-------------------
else:
---------------------
----------------------

Syntax-3: while loop in for loop


for varname in Iterable_object:

while (Test Cond):


else:
else:

70
Syntax-4: for loop in while loop
while(Test Cond):
-----------------------------
-----------------------------
for varname in Iterable_object:
-----------------------
-----------------------
else:
---------------------------
else:

String Handling Part-2


=>On String Data, we can perform Indexing, Slicing Operations and with these
operations, we can also perform different type of operations by using pre-defined
functions present in str object.
Pre-defined Functions in str object
1) capitalize()
=>This Function is used for capitalizing the first letter of First word of a given Sentence
only.
=>Syntax: strobj.capitalize()(OR)strobj=strobj.capitalize()
Examples:
>>> s="python" >>> print(s,type(s))->python <class 'str'>
>>> s.capitalize()->'Python'
>>> s="python is an oop lang">>> print(s,type(s))->python is an oop lang <class 'str'>
>>> s.capitalize()->'Python is an oop lang'
>>> s="python" >>> print(s,type(s))->python <class 'str'>
>>> s.capitalize()->'Python'

2) title():
=>This is used for obtaining Title Case of a Given Sentence (OR) Making all words First
Letters are capital.
Syntax: s.title()(OR)s=s.title()
Examples:
>>> s="python" >>> print(s,type(s))->python <class 'str'>
>>> s.capitalize()->'Python' >>> s.title()->'Python'
>>> s="python is an oop lang"
>>> print(s,type(s))->python is an oop lang <class 'str'>
>>> s.capitalize()->'Python is an oop lang'
>>> s.title()->'Python Is An Oop Lang' >>> print(s)->python is an oop lang
>>> s=s.title() >>> print(s)->Python Is An Oop Lang
3) index()
=>This Function obtains Index of the specified Value
71
=>If the specified value does not exist then we get ValueError
=>Syntax: strobj.index(Value)
=>Syntax: indexvalue=strobj.index(value)
Examples:
>>> s="python" >>> s.index("p")->0 >>> s.index("y")->1
>>> s.index("o")->4 >>> s.index("n")->5
>>> s.index("K")->ValueError: substring not found
=>enumerate() is one the general function, which is used for finding Index and Value of
an Iterable object.
NOTE:
>>> for i,v in enumerate(s):
... print("Index:{} and Value:{}".format(i,v))
OUTPUT
Index:0 and Value:p
Index:1 and Value:y
Index:2 and Value:t
Index:3 and Value:h
Index:4 and Value:o
Index:5 and Value:n
-----------------------------
>>> lst=[10,"Rossum",23.45,True]
>>> for i,v in enumerate(lst):
... print("Index:{} and Value:{}".format(i,v))
OUTPUT
Index:0 and Value:10
Index:1 and Value:Rossum
Index:2 and Value:23.45
Index:3 and Value:True
4) upper()
=>It is used for converting any type of Str Data into Upper Case.
=>Syntax:- strobj.upper()OR strobj=strobj.upper()
Examples:
>>> s="python" >>> print(s)->python >>> s.upper()->'PYTHON'
>>> s="python is an oop lang" >>> print(s)->python is an oop lang
>>> s.upper()->'PYTHON IS AN OOP LANG'
>>> s="Python IS an OOP lang"
>>> print(s)->Python IS an OOP lang
>>> s.upper()->'PYTHON IS AN OOP LANG' >>> s="AbCdEf"
>>> print(s)->AbCdEf >>> s.upper()->'ABCDEF'
>>> s="PYTHON" >>> print(s)->PYTHON >>> s.upper()->'PYTHON'
>>> s="123" >>> print(s)->123 >>> s.upper()->'123'

5) lower()
=>It is used for converting any type of Str Data into lower Case.
=>Syntax:- strobj.lower() OR strobj=strobj.lower()
72
Examples:
>>> s="Data Science" >>> print(s)->Data Science
>>> s.lower()->'data science'
>>> s="python" >>> print(s)->python >>> s.lower()->'python'
>>> s="PYTHON" >>> print(s)->PYTHON >>> s.lower()->'python'
>>> s="PYThon" >>> print(s)->PYThon >>> s.lower()->'python'
6) isupper()
=>This Function returns True provided the given str object data is purely Upper Case
otherwise it returns False.
Syntax: strobj.isupper()
Examples:
>>> s="PYTHON" >>> s.isupper()->True
>>> s="python" >>> s.isupper()->False
>>> s="Python" >>> s.isupper()->False
>>> s="PYThon" >>> s.isupper()->False
>>> s="123" >>> s.isupper()->False
>>> s="%$#^&@" >>> s.isupper()->False
7)islower()
=>This Function returns True provided the given str object data is purely lower Case
otherwise it returns False.
Syntax: strobj.islower()
Examples:
>>> s="pythopn" >>> s.islower()->True
>>> s="pythOn" >>> s.islower()->False
>>> s="PYTHON" >>> s.islower()->False
>>> s="123" >>> s.islower()->False
8) isalpha()
=>This Function returns True provided str object contains Purely Alphabets otherwise
returns False.
Syntax: strobj.isalpha()
Examples:
>>> s="Ambition" >>> s.isalpha()->True
>>> s="Ambition123" >>> s.isalpha()->False
>>> s="1234" >>> s.isalpha()->False
>>> s=" " >>> s.isalpha()->False
>>> s="#$%^@" >>> s.isalpha()->False
>>> s="AaBbZz" >>> s.isalpha()->True
9) isdigit()
=>This Function returns True provided given str object contains purely digits
otherwise returns False
Examples:
>>> s="python" >>> s.isdigit()->False
>>> s="python123" >>> s.isdigit()->False
>>> s="123" >>> s.isdigit()->True
>>> s="123 456" >>> s.isdigit()->False
73
>>> s="1_2_3" >>> s.isdigit()->False
>>> s="123KV" >>> s.isdigit()->False
10) isalnum()
=>This Function returns True provided str object contains either Alpabets OR
Numerics or Alpha-Numerics only otherwise It returns False.
=>Syntax: strobj. isalphanum()
=>Examples:
>>> s="python310" >>> s.isalnum()->True
>>> s="python" >>> s.isalnum()->True
>>> s="310" >>> s.isalnum()->True
>>> s="$python310" >>> s.isalnum()->False
>>> s="python 310" >>> s.isalnum()->False
>>> s="$python3.10" >>> s.isalnum()->False
>>> s="python3.10" >>> s.isalnum()->False
11) isspace()
=>This Function returns True provided str obj contains purely space otherwise it
returns False.
=>Syntax: strobj.isspace()
Examples:
>>> s=" " >>> s.isspace()->True
>>> s="" >>> s.isspace()->False
>>> s="python Prog" >>> s.isspace()->False
>>> s="Prasana Laxmi" >>> s.isspace()->False
>>> s.isalpha()->False >>> s.isalpha() or s.isspace()->False
12) split()
=>This Function is used for splitting the given str object data into different words base
specified delimter ( - _ # % ^ ^ , ; ....etc)
=>The dafeult deleimter is space
=>The Function returns Splitting data in the form of list object
=>Syntax: strobj.split("Delimter") (OR) strobj.split() (OR)
listobj= strobj.split("Delimter")(OR) listobj=strobj.split()
Examples:
>>> s="Python is an oop lang"
>>> print(s)->Python is an oop lang>>> s.split()->['Python', 'is', 'an', 'oop', 'lang']
>>> len(s.split())->5 >>> x=s.split()
>>> print(x,type(x))->['Python', 'is', 'an', 'oop', 'lang'] <class 'list'>
>>> len(x)->5 >>> s="12-09-2022"
>>> print(s)->12-09-2022 >>> s.split("-")->['12', '09', '2022']
>>> s="12-09-2022" >>> dob=s.split("-")
>>> print(dob,type(dob))->['12', '09', '2022'] <class 'list'>
>>> print("Day",dob[0])->Day 12
>>> print("Month ",dob[1])->Month 09
>>> print("Year ",dob[2])->Year 2022
---------------------------------------------------------
>>> s="Apple#Banana#kiwi/Guava"
74
>>> words=s.split("#") >>> print(words)->['Apple', 'Banana', 'kiwi/Guava']
>>> words=s.split("/") >>> print(words)->['Apple#Banana#kiwi', 'Guava']
13) join():
=>This Function is used for combining or joining list of values from any Iterable object
=>Syntax: strobj.join(Iterableobject)
Examples:
>>> lst=["HYD","BANG","AP","DELHI"]
>>> print(lst,type(lst))->['HYD', 'BANG', 'AP', 'DELHI'] <class 'list'>
>>> s=""
>>> s.join(lst)->'HYDBANGAPDELHI'
>>> s=" " >>> s.join(lst)->'HYD BANG AP DELHI'
-------------------------------------------------------------------
>>> t=("Rossum","is", "Father" "of" ,"Python")
>>> print(t,type(t))
('Rossum', 'is', 'Fatherof', 'Python') <class 'tuple'>
>>> k=" "
>>> k.join(t)
'Rossum is Fatherof Python'
>>> t=("Rossum","is", "Father", "of" ,"Python")
>>> k=" "
>>> k.join(t)
'Rossum is Father of Python'

Functions in Python
Index
=>Purpose of Functions
=>Advantages of Functions
=>Definition of Functions
=>Parts of Functions
=>Phases in Functions
=>Syntax for Defining Functions
=>Number of Approaches for Defining Functions
=>Programming Examples
----------------------------------------------------------------------------------------------------
=>Arguments and Parameters
=>Types of Arguments and Parameters
a) Positional Arguments and Parameters
b) Default Arguments and Parameters
c) Keyword Arguments and Parameters
d) Variable Length Arguments and Parameters
e) Keyword Variable Length Arguments and Parameters
=>Programming Examples
---------------------------------------------------------------------------------------------------
=>Global Variables and Local Variables
75
=>global keyword and globals()
=>Programming Examples
=>Anonymous Functions OR Lambda Functions
=>Programming Examples
--------------------------------------------------------------------------------------------------
=>Special Function in Python
a) filter() with Normal and Anonymous Functions
b) map() with Normal and Anonymous Functions
c) reduce() with Normal and Anonymous Functions
=>Programming Examples

Types of Languages in the context of Functions


=>In IT, we have two types of Programming Languages. They are
1. Un-Structured Programming Languages
2. Structured Programming Languages

1. Un-Structured Programming Languages


=>Un-Structured Programming Languages does not contain the concept of Functions
and hence whose applications having the following Limitations.

1. Application Development time is More


2. Application Memory Space is More
3. Application Execution Time is More
4. Application Performance is degraded
5. Redundancy of the code is More

Examples: GW-BASIC

2. Structured Programming Languages


=>Structured Programming Languages contains the concept of Functions and
hence whose applications having the following Advantages.

1. Application Development time is Less


2. Application Memory Space is Less
3. Application Execution Time is Less
4. Application Performance is Enhanced (Improved)
5. Redundancy of the code is Minimized

Examples: C,C++,Java, PYTHON.....etc


Functions in Python
=>The Purpose of Functions is that " To Perform Certain Operation and provides
Code Re-Usability ".
=>Definition of Function:
=>A part of main program is called Function (OR)
=>Sub Program of Main Program is called Function.
76
Parts of Functions
=>When we are dealing with Functions, we must ensure that, there must exist Two
parts. They are
1. Function Definition
2. Function Call(s)
=>Here Particular Function Definition Exist Only Once
=>For Every Function Call There Must Exist Function Definition otherwise we get
NameError.
=> Function Definition Can’t Execute by itself but there are executed through a function
call. In Other-words Function Definition will be executed when we call the Function by
using Function Call.
Phases in Functions
=>At the time Defining the functions, we must ensure that there must exist 3 Phases.
1. Every Function must take INPUT
2. Every Function must PROCESS the input
3. Every Function must give RESULT / OUTPUT
Number of Approaches to Define a Function
=>If any Problem Statement is given then it be solved by using Function in 4
Approaches. They are
Approach1:
=>INPUT Taking from Function Call
=>PROCESSING done in Function Body
=>OUTPUT / RESULT giving to Function Call
Examples:
#Program for defining a function for addition of two numbers
#ApproachEx1.py
def addop(a,b): # Here 'a' and 'b' are called Formal Parameters
c=a+b # Here 'c' is called Local variable
return c # here return statement is used for giving the result back

#main program
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
res=addop(x,y) # Function Call
print("sum({},{})={}".format(x,y,res))
Approach2:
=>INPUT Taking in Function Body
=>PROCESSING done in Function Body
=>OUTPUT / RESULT displaying in Function Body
Examples:
#Program for defining a function for addition of two numbers
#ApproachEx2.py
def addop():
a=float(input("Enter First Value:"))
77
b=float(input("Enter Second Value:"))
c=a+b
print("sum({},{})={}".format(a,b,c))

#main program
addop() # Function Call
Approach3:
=>INPUT Taking in Function Body
=>PROCESSING done in Function Body
=>OUTPUT / RESULT giving to Function Call
Examples:
#Program for defining a function for addition of two numbers
#ApproachEx3.py
def addop():
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
c=a+b
return a,b,c # In Python, return stmt can return one or more values

#main program
a,b,c=addop() # Function Call with multi line assigment
print("sum({},{})={}".format(a,b,c))
print("----------------------------------------------------------")
kvr=addop() # Here kvr is an object of type tuple.
print("sum({},{})={}".format(kvr[0],kvr[1],kvr[2]))
Approach4:
=>INPUT Taking from Function Call
=>PROCESSING done in Function Body
=>OUTPUT / RESULT displaying in Function Body
Examples:
#Program for defining a function for addition of two numbers
#ApproachEx4.py
def addop(a,b):
c=a+b
print("sum({},{})={}".format(a,b,c))

#main program
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
addop(a,b) # Function Call

Arguments and Parameters


=>Parameters represents list of Variables used in Function Heading and they are used
for Storing the inputs coming Functions Calls and these Parameters are called Formal
Params Meters.
78
=>Arguments are the Variables used inside of Function Call(s) and they are also called
Actual Arguments.

Syntax for Function Definition


def functionname(param1,param2...param-n):
--------------------------------------

Syntax for Function Call


functionname(args1,args2.......args-n)
=>Hence relationship between arguments and Parameters is that Every Value of
arguments are passing Parameters.
Types of Arguments and Parameters
=>Based on Passing the values of Arguments from Function Calls to Parameters of
Function Definition, Arguments and Parameters are classified into 5 types. They are

1. Positional Arguments OR Parameters


2. Default Arguments OR Parameters
3. Keyword Arguments OR Parameters
4. Variable Length Arguments OR Parameters
5. Keyword Variable Length Arguments OR Parameter

1) Positional Arguments (or) Parameters


=>The Concept of Positional Parameters (or) arguments says that "The Number of
Arguments(Actual arguments ) must be equal to the number of formal parameters ".
=>This Parameter mechanism also recommends Order and Meaning of Parameters for
Higher accuracy.
=>To pass the Specific Data from Function Call to Function Definition then we must
take
Positional Argument Mechanism.
=>The default Argument Passing Mechanism is Positional Arguments (or) Parameters.
Syntax for Function Definition:
def functionname(parm1,param2.....param-n):
-------------------------------------------------
-------------------------------------------------

Syntax for Function Call:


functionname(arg1,arg2....arg-n)

=>Here the values of arg1,arg2...arg-n are passing to param-1,param-2..param-n


respectively.
=>PVM gives First Priority for Possitional Arguments (or) Parameters

2) Default Parameters (or) arguments

79
=>When there is a Common Value for family of Function Calls then Such type of
Common Value(s) must be taken as default parameter with common value (But not
recommended to pass by using Positional Parameters)

Syntax: for Function Definition with Default Parameters


----------------------------------------------------------------------------------------
def functionname(param1,param2,....param-n-1=Val1, Param-n=Val2):
------------------------------------------------------------------
------------------------------------------------------------------
Here param-n-1 and param-n are called "default Parameters"
and param1,param-2... are called "Positional parameters"

Rule-: When we use default parameters in the function definition, They must be used as
last Parameter(s) otherwise we get Error( SyntaxError: non-default argument
(Possitional ) follows default argument).
3) Keyword Parameters (or) arguments
=>In some of the circumstances, we know the function name and formal parameter
names and we don't know the order of formal Parameter names and to pass the data /
values accurately we must use the concept of Keyword Parameters (or) arguments.
=>The implementation of Keyword Parameters (or) arguments says that all the formal
parameter names used as arguments in Function call(s) as keys.

Syntax for function definition: -


def functionname(param1,param2...param-n):

Syntax for function call:-


functionname(param-n=val-n,param1=val1,param-n-1=val-n-1,.........)

Here param-n=val-n,param1=val1,param-n-1=val-n-1,...... are called Keywords


arguments
4) Variables Length Parameters (or) arguments
=>When we have familiy of multiple function calls with Variable number of values /
arguments then with normal python programming, we must define mutiple function
defintions. This process leads to more development time. To overcome this process, we
must use the concept of Variable length Parameters.
=>To Impelement, Variable length Parameters concept, we must define single Function
Definition and takes a formal Parameter preceded with a symbol called astrisk ( *
param) and the formal parameter with astrisk symbol is called Variable length
Parameters and whose purpose is to hold / store any number of values coming from
similar function calls and whose type is <class, 'tuple'>.
Syntax for function definition with Variables Length Parameters:
def functionname(list of formal params, *param1,param2=value) :
--------------------------------------------------

80
=>Here *param is called Variable Length parameter and it can hold any number of
argument values (or) variable number of argument values and *param type is
<class,'tuple'>
=>Rule:- The *param must always written at last part of Function Heading and it must
be only one (but not multiple)
=>Rule:- When we use Variable length and default parameters in function Heading, we
use default parameter as last and before we use variable length parameter and in
function calls, we should not use default parameter as Key word argument bcoz
Variable number of values are treated as Posstional Argument Value(s) .
5) Key Word Variables Length Parameters (or) arguments
=>When we have familiy of multiple function calls with Key Word Variable number of
values / arguments then with normal python programming, we must define mutiple
function defintions. This process leads to more development time. To overcome this
process, we must use the concept of Keyword Variable length Parameters .
=>To Implement, Keyword Variable length Parameters concept, we must define single
Function Definition and takes a formal Parameter preceded with a symbol called
double astrisk ( ** param) and the formal parameter with double astrisk symbol is
called Keyword Variable length Parameters and whose purpose is to hold / store any
number of (Key,Value) coming from similar function calls and whose type is <class,
'dict'>.
Syntax for function definition with Keyword Variables Length Parameters:
def functionname(list of formal params, **param) :
--------------------------------------------------
--------------------------------------------------

=>Here **param is called Keyword Variable Length parameter and it can hold any
number of Key word argument values (or) Keyword variable number of argument
values and **param type is <class,'dict'>

=>Rule:- The **param must always written at last part of Function Heading and it must
be only one (but not multiple)
Final Syntax for defining a Function
def funcname(PosFormal parms, *Varlenparams, default params, **kwdvarlenparams):
Global Variables and Local Variables
Local Variables
=>Local Variables are those which are used in side of Function Body and they are used
for storing Temporary result of Processing Logic.
=>We can access the value of Local Variables Inside of Function Body only but no other
part of the program.
Global Variables
=>Global variables are those are they are used for accessing as common values in
Multiple Different function Calls
=>Global Variables Must be defined before all Function Calls. so that we can Global
Variables values in correspondinf Function Definitions.
81
=>if we define Global Variables after all Function Calls then we can't access Global
Variables values in correspondinf Function Definitions( NameError we get).
global key word
=>When we want MODIFY the GLOBAL VARIABLE values in side of function defintion
then global variable names must be preceded with 'global' keyword otherwise we get
"UnboundLocalError: local variable names referenced before assignment"

Syntax:
var1=val1
var2=val2
var-n=val-n # var1,var2...var-n are called global variable names.
------------------
def fun1():
------------------------
global var1,var2...var-n
# Modify var1,var2....var-n
--------------------------
def fun2():
------------------------
global var1,var2...var-n
# Modify var1,var2....var-n
--------------------------
Examples:
#globalvarex1.py
a=10
def access1():
print("Val of a=",a) # Here we are accessing the global variable 'a' and No Need
to use global kwd.

#main program
access1()
---------------------------------------
#globalvarex2.py
a=10
def access1():
global a # refering global Varaible before its updation / Modification
a=a+1 # Here we are modifying the global variable value then we need to use
global keyword.
print("Val of a inside of access1()=",a) # 11
#main program
print("Val of a in main before access1():",a) # 10
access1()
print("Val of a in main after access1():",a) # 11
---------------------------------------------------------------------------------
Examples:
82
#globalvarex3.py
def update1():
global a,b # refering global Variables.
a=a+1 #updating global Variable a
b=b+1 #updating global Variable b
def update2():
global a,b # refering global Variables.
a=a*10 #updating global Variable a
b=b*10 #updating global Variable b

#main program
a,b=1,2 # here a and b are called Global Variables
print("Val of a={} and Value of b={} in main program before update
functions :".format(a,b))
# Val of a=1 and Value of b=2 in main program before update functions :
update1()
print("Val of a={} and Value of b={} in main program after update1():".format(a,b))
#Val of a=2 and Value of b=3 in main program after update1():
update2()
print("Val of a={} and Value of b={} in main program after update2():".format(a,b))
#Val of a=20 and Value of b=30 in main program after update1():
global and local variables and globals()
=>When we come across same global Variable names and Local Variable Names in
same function definition then PVM gives preference for local variables but not for
global variables.
=>In this context, to extract / retrieve the values of global variables names along with
local variables, we must use global () and it returns an object of <class,'dict'> and this
dict object stores all global variable Names as Keys and global variable values as values
of value.

=>Syntax:-
var1=val1
var2=val2
--------------
var-n=val-n # var1, var2...var-n are called global Variables
def functionname():
------------------------
var1=val11
var2=val22
-----------------
var-n=val-nn # var1, var2...var-n are called local Variables
# Extarct the global variables values
dictobj=globals()
------------------------

83
globalval1=dictobj['var1'] # or dictobj.get("var1") or globals()
['var1']
globalval2=dictobj['var2'] # or dictobj.get("var2") or globals()
['var2']
-----------------------------------------------------
Examples:
#globalsfunex3.py
a=10
b=20
c=30
d=40
def operations():
obj=globals()
for gvn,gvv in obj.items():
print("\t{}---->{}".format(gvn,gvv))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj['a'])
print("Val of b=", obj['b'])
print("Val of c=", obj['c'])
print("Val of d=", obj['d'])
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj.get('a'))
print("Val of b=", obj.get('b'))
print("Val of c=", obj.get('c'))
print("Val of d=", obj.get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals().get('a'))
print("Val of b=", globals().get('b'))
print("Val of c=", globals().get('c'))
print("Val of d=", globals().get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals()['a'])
print("Val of b=", globals()['b'])
print("Val of c=", globals()['c'])
print("Val of d=", globals()['d'])
print("="*50)
=================================================
84
#main program
operations()
Examples:
#Program for demonstrating globals()
#globalsfunex2.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called Global Variables
def operation():
a=100
b=200
c=300
d=400 # Here a,b,c,d are called Local Variables
res=a+b+c+d+globals()['a']+globals().get('b')+globals()['c']+globals()['d']
print(res)

#main program
operation()

Anonymous Functions OR Lambda Functions


=>Anonymous Functions are those which does not contain Name Explicitly.
=>The purpose of Anonymous Functions is that " To Perform Instant Operations".
=>Instant Operations are those Which are used at that Point Time Only But No Longer
interested to use next Part of the project".
=>To define Anonymous Functions, we use lambda keyword and hence Anonymous
Functions are called Lamda Functions.
=>Anonymous Functions contains Single executable Statement Only but never contains
Multiple Executable Statements.
=>Anonymous Functions automatically or Implcitly returns the value (No Need to use
return statement)
Syntax: varname=lambda params-list : statement
----------------------------------------------------------------------------------
Explanation
=>Here Varname is an object of <class, 'function'> and varname indirectly treated as
Anonymous Function Name.
=>Here lambda is Keyword used for Defining Anonymous Functions
=>Params-list represents list of Variable Names used for Holding / Storing the inputs
coming from Functions.
=>Gere Stetement represents Single Executable Statement and whose Value returns
Automatically or Implicitly.
---------------------------------------------------------------------------------------------
Question: Define a Function for adding two values

85
Normal Function---Definition Anonymous Function
------------------------- -------------------------------
def sumop(a,b): sumop=lambda a,b:a+b
c=a+b
return c
---------------------------
Main program main program
---------------------- -----------------------
res=sumop(10,20) # Function Call res=sumop(3,4)
print(res)----30 print(res)

List comprehension
=>The purpose of List comprehension is that to read the values dynamically from key
board separated by a delimeter ( space, comma, colon..etc) .
=>List comprehension is the most effective way for reading the data for list instead
tradtional reading the data and also we can perform Various Operations.
=>Syntax:- listobj=[ expression for varname in Iterable_object ]
=>here expression represents either type casting or mathematical expression
Examples:
print("Enter List of values separated by space:") # [10,2,222,50,10,4,55,-3,0,22]
lst= [float(val) for val in input().split() ]
print("content of lst",lst)

Examples:
lst=[4,3,7,-2,6,3]
newlst=[ val*2 for val in lst ]
print("new list=",newlst) # [ 8, 6, 14,-4,12,6 ]
Special Functions in Python
=>In Python Programming, we have 3 Types of Special Functions. They are
1) filter() 2) map() 3) reduce()

1) filter()
=>The purpose of filter() is that " To filter out some elements from given list of
elements based on some condition".
=>Syntax: varname=filter(FunctionName , IterableObject )
=>Here varname is an object of <class, 'filter'>. Programatically we can convert an
object of filter into Sequence , List, set and dict type by using Type Casting Functions.
=>filter() is one of the pre-defined special function.
=>Function Name can be either Normal Function or Anonymous Function.
=>Iterable Object can any Sequence , List, set and dict type
=>The Execution Process of filter() is that " Each Element of Iterable object passing to
Specified Function Name, Function Name Takes that value, appiled to the condition, If
the condition is True then that Element filtered otherwise the element will be
neglected". This Process will be repeated until all elements of Iterable object
completed.
86
2) map()
=>map() is used for obtaining new Iterable object from existing iterable object by
applying old iterable elements to the function.
=>In otherwords, map() is used for obtaining new list of elements from existing
existing list of elements by applying old list elements to the function.

=>Syntax:- varname=map(FunctionName,Iterable_object)

=>here 'varname' is an object of type <class,map'> and we can convert into any
iteratable object by using type casting functions.
=>"FunctionName" represents either Normal function or anonymous functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of map() is that " map() sends every element of iterable object
to the specified function, process it and returns the modified value (result) and new list
of elements will be obtained". This process will be continued until all elements of
Iterable_object completed.
3.reduce()
=>reduce() is used for obtaining a single element / result from given iterable object by
applying to a function.
=>Syntax:-
varname=reduce(function-name,iterable-object)
=>here varname is an object of int, float,bool,complex,str only
=>The reduce() belongs to a pre-defined module called" functools".
Internal Flow of reduce()
step-1:- Initially, reduce() selects First Two values of Iterable object and place them in
First
var and Second var .
step-2:- The function-name(vlambda or normal function) utilizes the values of First var
and Second var and applied to the specified logic and obtains the result.
Step-3:- reduce () places the result of function-name in First variable and reduce()
selects the succeeding element of Iterable object and places in second variable.
Step-4: Repeat Step-2 and Step-3 until all elements completed in
Iterable object and returns the result of First Variable.
--------------------------------------------------------------------

87

You might also like