02 Python Notes
02 Python Notes
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
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)
=>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
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
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
>>> 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 )
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)
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 )
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)
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)
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
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}
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=================================
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:
>>> d1[100]="Guido"
>>> print(d1,type(d1),len(d1), id(d1))-----{100: 'Guido', 101: 'Ritche', 102: 'Travis', 103:
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]
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
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
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
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)
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
=>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
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
1) and :
56
=>The Functionality of "and" operator is described in the following Truth Table.
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
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
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 sFalse
>>> "HON" not in sFalse
>>> "NOH" in sFalse
>>> "OTP" in sFalse
>>> "OTP" not in sTrue
>>> "NOH" in s[::-1]True
>>> "OTP" not in s[::-2]True
>>> s[::-2]'NHY'
>>> s in sTrue
>>> 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
=============================================
65
Flow Control Statements in Python
Index
=>Purpose of Flow Control Statements in Python
=>Types of Control Statements in Python
#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:
-----------------------------------
70
Syntax-4: for loop in while loop
while(Test Cond):
-----------------------------
-----------------------------
for varname in Iterable_object:
-----------------------
-----------------------
else:
---------------------------
else:
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
Examples: GW-BASIC
#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
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)
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.
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()
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