Python Programming
Unit I
Introduction to Python
• Python is a high level, interpreted, general
purpose ,dynamic programming language.
• Conceived in late 80s and its usage began in
1989.
• It is a free and open software
• Open source software: is a kind of software in
which the source code of the software is made
public. It is a community based development.
• Fewer lines of code when compared to C ,C++
and JAVA.
• It Supports automatic memory management
• Has large standard library
• Can be used in any OS as the interpreter is
available for many OS- platform independent
• Can be used in Object oriented, Functional
programming, Procedural programming
• Reusability
Features of Python
• The code written python is automatically
compiled to bytecode and executed.
• Can be used as Scripting language
• Uses Object oriented programming approach
• Supports features like nested code blocks,
functions, classes, modules and packages
• Has built in data types like strings, lists, tuple,
dictionaries
• No type declaration
• Python program can be extended
IDLE
• IDLE (Integrated Development and Learning
Environment) is an integrated development
environment (IDE) for Python.
• The Python installer for Windows contains the
IDLE module by default.
• IDLE is not available by default in Python
distributions for Linux. It needs to be installed
using the respective package managers.
• IDLE can be used to execute a single
statement just like Python Shell and also to
create, modify and execute Python scripts.
• IDLE provides a fully-featured text editor to
create Python scripts that includes features
like syntax highlighting, autocompletion and
smart indent. It also has a debugger with
stepping and breakpoints features.
• Anoconda jupyter notebook,spyder
/* my first c pgm */
void main()
{
int x; /* variable declaration */
for (i; i>10;i++)
printf( indent
}
Python - Shell (Interpreter)
• Python is an interpreter language. It means it
executes the code line by line. Python
provides a Python Shell (also known as Python
Interactive Shell) which is used to execute a
single Python command and get the result.
• Python Shell waits for the input command
from the user. As soon as the user enters the
command, it executes it and displays the
result.
Comments
• Comments are annotations made by the
programmer helping other programmers
understand the code
• Python uses the hash character(#) for comments
• # is put before the text and hence will not be
parsed by the interpreter.
• No error message will be displayed
• Does not affect the programming part
• >>> 3+5 addition
• This shows syntax error
• >>> 3+5 #addition commands
• No error and output displayed as 8
Identifiers
• It is a name given to variable, function, class, module or
other object etc
• Can begin with uppercase or lowercase letters or an
Underscore with a combination of any number of letters,
digits or underscores
• No other special characters are allowed
• Spaces are not allowed
• Python is a case sensitive language
Eg: Hello and hello different variables
• Class name starts with a uppercase letter
• Examples
• Valid:
MyName, My_Name , _myName
• Invalid:
My Name, 3rdYear, Your#Name
Reserved Words
• Also known a keywords
• Has special meaning (purpose) and use
• They cannot be used as identifiers >>>help(“for”)
• Here is a list of the Python keywords
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
Variables
• A variable hold a value that may change
• Variables in Python need not be explicitly
declared to reserve memory spaces as in other
languages
• When the variable is initialized, the interpreter
automatically does the declaration process
• Thus naming the variable is called declaration
of the variable
Initializing the variable
• A value is bound to a name by the assignment
operator '='.
• Syntax
Variable = expression
• = is the assignment operator
• Variable is the name of the variable
• expression is any value, text or arithmetic exp
• The value of the expression is stored in the variable
• Egs
>>> year=2016
>>>name=‘Albert’
• Can assign value of one variable to another
Eg:
>>>name1= ‘Albert’
>>>name2=name1
>>>name2
‘Albert’
>>>name1
‘Albert’
>>>year=2016
>>>year=2020
>>>year
2020
Data types
• Data types are the classification or
categorization of data items.
• Data types represent a kind of value which
determines what operations can be performed
on that data.
• Numeric, non-numeric and Boolean
(true/false) data are the most used data types.
Python has 6 basic data types
• Numeric
• String
• List
• Tuple
• Dictionary
• Boolean
Numeric Data type
• A numeric value is any representation of data
which has a number associated with it
Three types of numbers:
• Integer: Positive or negative whole numbers
• Float: Any real number with a floating point
representation in which a fractional component is
denoted by a decimal symbol or scientific notation
• Complex number: A number with a real and
imaginary component represented as x+iy.
• There is no upper bound for the numeric data
types
>>> num1= 2
>>>num2=2.5
>>>num1
2
>>>num2
2.5
• In earlier versions before Python 3
>>>5/2
2
>>>5.0/2 >>>5/2.0 >>>5.0/2.0
2.5
• But in Python3
>>>5/2
2.5
String
• A string value is a collection of one or more
characters put in single, double or triple
quotes.
• The first character of the string has the index
value 0
Operators on String
• Slice [ ] [:]
• Concatenation +
• Repetition *
>>> str1=“Hello”
>>>str1
‘Hello’
>>> str1 + “World”
‘HelloWorld’
>>> str1 * 3
‘HelloHelloHello’
Slicing- to take out subset of the string
• Syntax
>>> str1[start : end < : step > ] # step is optional
Egs
>>>str1[1] Hello
‘e’
>>>str1 [0: 2]
‘He’
>>>samplestr = ‘HelloWorld’
>>>samplestr[ 1:8 :2 ]
‘elWr’
# Displays alternate characters in the range 1 to 8
Lists
• A list object is an ordered collection of one or
more data items, not necessarily of the same
type, put in square brackets, separated by
commas
# this is difference between an array in C
• It is ordered and indexable sequence
• Lists are mutable
>>> first = [1, ”two”, 3.0 ]
>>> second = [ “four”, 5]
>>> first
[1, ‘two’, 3.0 ]
Operations on lists
+
>>> first + second
[1, ‘two’, 3.0, ‘four’, 5 ]
Slice
>>>first[0:2]
[1, ‘two’]
Repition
>>>second * 2
[‘four’, 5 ,‘four’, 5 ]
Tuple
• A Tuple object is an ordered collection of one
or more data items, not necessarily of the
same type, put in parentheses.
Egs
>>>third=( 6,”seven”, 8, “nine”,10.0)
>>>third
( 6,’seven’, 8, ‘nine’,10.0)
• >>> first[0]=“one”
• >>>third[0]=“six” #produces error
• immutable
Dictionary
• A dictionary object is an unordered collection
of data in a key:value pair form.
• A collection of such pairs is enclosed in curly
brackets. { }
• Iterating is possible over
– Keys
– Values
– Key-value pairs or item
• Used when there is large amt of data
• Used when there is large amt of data
• Keys and values can be of any data type
• Colon is used to separate the key value pair
• The key inside the [ ]is used to access the
dictionary items
• mutable
>>>dict1={1:”first”, “second”:2}
>>>dict1[3]= “third line”
>>>dict1
{1:”first”, “second:2”, 3: “third line”}
>>>dict1.keys()
[1, “second”, 3]
>>> dict1.values()
[”first”, 2, “third line”]
Boolean
• Data with one of two built-in values:
True or False
>>> a = True
>>> type(a)
< type ‘bool’>
>>> x = False
>>> type(x)
< type ‘bool’>
Sets
• A set is a collection of data types in Python,
same as the list and tuple.
• it is not an ordered collection of objects.
• The set is a Python implementation of the set
in Mathematics.
• A set object has suitable methods to perform
mathematical set operations like union,
intersection, difference, etc.
• A set does not contain duplicate values
>>> set1= set([1,2,4,1,2,8,5,4])
>>>set2= set([1,9,3,2,5])
>>> print set1
set([8,1,2,4,5])
>>>print set2
set([1,2,3,5,9])
>>>intersection = set1 & set2
>>> print intersection
set([1, 2, 5])
>>> union=set1|set2
>>>difference=set1-set2
>>>symm_diff=set1^set2
type()
• Python has an in-built function type() to
ascertain the data type of a certain value.
>>> type(1234)
<class 'int'>
which means 1234 is an integer value.
>>> tup= (1,2,3)
>>>type(tup)
<type ‘tuple'>
>>>x=10
>>>y=12
>>>z=0
>>>z=x+y
>>>print z
22
>>>z=x/y
>>>print z
0
>>>z=x%y
>>>print z
10
>>>z=x**y
>>>print z
1000000000000
>>>z=x//y
>>>print z
0
COMPARISON OPERATOR
• Used to compare values
• Also called relational operators
• Result is boolean value; True/ False
OPERATOR EXAMPLE
== 10==20, False
!= or <> 10!=20 , True
> 10>20 , False
< 10<20, True
>= 10>=20 , False
<= 10<=20, True
>>>if(x==y): #x=10 y=12
print “x is equal to y”
else :
print “x not equal to y”
OUTPUT:
x is not equal to y
ASSIGNMENT OPERATORS
• Used to store RHS value in the left side
operand. a- =b a=a-b
OPERATOR EXAMPLE
= a=b+c
+= a+=b
-= a-=b
*= a*=b
/= a/=b
%= a%=b
**= a**=b
//= a//=b
LOGICAL OPERATORS
• Used to check two or more conditions.
• The result is boolean.
• Assume x is true and y is false x and y
OPERATOR EXAMPLE
and (logical AND) x and y, false
or (logical OR) x or y, true
not (logical NOT) not x, false
It can be used to form complex compound
expression
MEMBERSHIP OPERATORS
• Used to check whether an item or element is
part of a string, a list or a tuple.
• Reduces the effort of searching an element in
the list.
• Let x=20 and y be a list with 10, 20 ,30, and 40
OPERATOR EXAMPLE
in x in y, true
not in x not in y, false
IDENTITY OPERATORS
• Used to check whether both operands are
same or not.
• Suppose x =20 and y=40
OPERATOR EXAMPLE
is x is y, false
not is x not is y, true
PRECEDENCE OF OPERATORS
• When there are two or more operators in an
expression, we need to identify the correct
sequence to evaluate the operators.
• Precedence is a condition specifying the
importance of each operator relative to others
• (x +2)*23-z x+46-z
OPERATORS
NOT, OR, AND
IN, NOT IN OPERATOR PRECEDENCE FROM LOWER TO
HIGHER.
IS, NOT IS
=, %=,/=, //=, -=, +=, *=,**=
<>, ==, !=
^, |
&
<<,>>
+,-
*,/,%,//
**
ASSOCIATIVITY
• It decides the order in which, operators with
the same precedence are executed x-4+5
• Two types : left-to-right and right-to-left
Left-to-Right
• The operator of same precedence are
executed from the left side first. Eg; *,// etc
Right-to-Left
• The operator of same precedence are
executed from the right side first. Eg; ** etc
>>>3 * 4 // 6
2
>>>3 * (4//6)
0
>>>3 ** 4 ** 2
43046721
>>> (3**4) ** 2
6561
• The order in which operators are evaluated can be
controlled using parentheses as highest precedence.
• When two operators have the same precedence, they are
evaluated from left to right.
Example, 10*5/5
OPERATORS
• Unary operator
uses only one operand.
used to give sign to the operand
syntax :
operator operand
unary operators are +,-, ~
• Binary Operator
operator which uses two operands
used to compare numeric and string values
syntax :
operand1 operator operand2
STATEMENT
• A statement is a unit of code that the Python
interpreter can execute.
• Instruction that can be interpreted by python
interpreter and result which is displayed.
• A program contains many statements in sequence.
• If there are multiple statements, the result is displayed
after every statement.
print 1 produces output
x=2 1
print x 2
• There are different types of statements like
assignment statement, return statement,
break statement, for statement, if statement,
while statement etc
• The assignment statement produces no
output
• Statements in python can be extended to multiple lines using
parentheses (), braces {}, square brackets [], semi colon ; or
continuation character slash can be used.
s= 1+2+3+ \
4+5+6+ \
7+8+9
x = { 1+ 2 + 3 + 4 + 5 +
6+7+8+9}
n=(1*2*3+7+8)
flag=2; ropes=3; pole=4
• A block is combination of statements.
ie grouping of statements for a specific
purpose.
• Python uses indentation to highlight blocks
• Whitespace is used for indentation in Python
• All statements with the same distance from
the right belong to the same block of code.
• If a block is more nested, it should be indented
further to the right.
def iseven(num):
if num % 2 ==0:
return True
else:
return False
num = int(input(‘enter a number’))
if iseven(num) is True:
print(num,’is an even number’)
else:
print(num,’is an odd number’)
EXPRESSION
• Combination of variables, expressions, values
and reserved keywords.
• The interpreter evaluates an expression and
produces the result.
• An expression need not be always a
mathematical expression.
• A value by itself is an expression
• Example arithmetic exp, boolean exp
• 4 + ( 3 + k) is a valid exp in Python.
• It has two sub exps 4 and ( 3 + k)
• The sub exp ( 3 + k) itself has two expressions ie 3
and k
• A sub exp is any exp that is part of a larger exp
• Since a sub exp itself is a exp, a sub exp may
contain sub exps of its own.
• Sub exps is denoted by the use of parentheses
• If no parentheses is used then an exp is evaluated
according to the rules of operator precedence.
• Expressions that evaluate to a numeric type
are called arithmetic expressions
4+(3*2)
Two operands 4 and (3*2)
(4+3)*2
Two operands (4+3) and 2
• Boolean expression is an exp that evaluates to
a boolean value, denote as True and False.
• Denote conditions for selection and iterative
controls statements
USER INPUTS
• Python programming language allows the user to provide input
from the keyboard.
• Done in two ways :
• input () function
syntax : input ([prompt])
• this has an optional parameter which is the prompt string.
the input function reads a line entered on the console by an
input device such as a keyboard and converts it into a string and
returns it.
• when the input function is executed, the program flow stops
until the user enters some value.
• (the string returned by the input function sometimes needs to
be converted to the desired data type – in python 3)
>>>input(“enter your name”)
>>>name= input (“what is you name?”)
>>>print (“Hello ”+ name+“!”)
Output:
what is your name? ‘John’
Hello John!
>>>age= input (“enter your age”)
>>>print age +10
Output :
enter your age 32
error
a= input (“Enter a String:”)
b= input (“Enter an integer number:”)
c= input (“Enter an floating number:”)
print(“Type of a is”, type(a))
print(“Type of b is”, type(b))
print(“Type of c is”, type(c))
Output:
Enter a String: Hello
Enter an integer number: 20
Enter an floating number: 45.35
Type of a is <class ‘str’>
Type of b is <class ‘str’>
Type of c is <class ‘str’>
Numbers have to be explicitly typecast.
num1 = int(input(“enter an integer:”))
num2 = float(input(“enter a floating value”))
raw_input () Function:
• It takes input but it does not interpret the input and returns the
input without doing any changes.
• The user needs to use casting function to convert to the desired
data type.
>>>age= raw_input (“what is your age?”)
what is your age? 46
>>>type (age)
<type ‘str’>
>>>age= int (raw_input (“what is your age?”))
what is your age? 46
>>>type (age)
<type ‘int’>
PRINT FUNCTION
• The print() function prints the specified message
to the screen, or other standard output device.
• The message can be a string, or any other object
• The object will be converted into a string before
written to the screen.
Syntax:
print(object(s), sep=separator, end=end, file=file,
flush=flush)
object(s) Any object, and as many objects as
you like. Will be converted to string
before printed
sep='separator' Optional. Specify how to separate
the objects, if there is more than one.
Default is ' '
end='end' Optional. Specify what to print at the
end. Default is '\n' (line feed)
file Optional. An object with a write
method. Default is sys.stdout
flush Optional. A Boolean, specifying if the
output is flushed (True) or buffered
(False). Default is False
>>>print()
This produces a invisible newline character,
which in turn will cause a blank line to appear
on the screen
>>>print(“Enter the marks of the student”)
Or
>>>message=“Enter the marks of the student”
>>>print(message)
• print("Hello", "how are you?")
Hello how are you?
Here there are 2 arguments and prints output
with a space in between.
• x = ("apple", "banana", "cherry")
• print(x)
('apple', 'banana', 'cherry')
• print("Hello", "how are you?", sep="---")
Hello---how are you?
>>>print('hello','world',sep=None)
>>>print('hello','world',sep=’ ‘)
>>>print('hello','world')
These 3 statements give the same result
hello world
>>>print('hello','world',sep=’’)
Gives the result
helloworld
>>>print('hello','world',sep=’\n‘)
hello
world
>>>print('documents','python',’program’,sep=’/ ‘)
Here there are 3 arguments with separator /
documents/python/program
>>>print('/documents','python',’program’,sep=’/ ‘)
/documents/python/program
String Format()
• The format() method allows you to format
selected parts of a string.
• To control the way the output is printed, add
placeholders (curly brackets {}) in the text, and
run the values through the format() method
>>>price = 49
>>>txt = "The price is {} dollars“
>>>print(txt.format(price))
The price is 49 dollars.
• You can add parameters inside the curly
brackets to specify how to convert the value
>>>price = 49
>>>txt = "The price is {:.2f} dollars"
>>>print(txt.format(price))
The price is 49.00 dollars
• If you want to use more values, just add more
values to the format() method and if needed
add place holders.
print(txt.format(price, itemno, count))
>>>quantity = 3
>>itemno = 567
>>>price = 49
>>>myorder = "I want {} pieces of item number
{} for {:.2f} dollars."
>>>print(myorder.format(quantity, itemno,
price))
I want 3 pieces of item number 567 for 49.00
dollars.
• Index numbers can be used(a number inside the curly
brackets {0}) to be sure the values are placed in the
correct placeholders
Example:
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for
{2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Output
I want 3 pieces of item number 567 for 49.00 dollars.
• The same value can be referred more than
once, using the index number
>>>age = 36
>>>name = "John"
>>>txt = "His name is {1}. {1} is {0} years old."
>>>print(txt.format(age, name))
>>>myorder = "I have a {carname}, it is a
{model}.
>>>print(myorder.format( carname="Ford",
model = "Maruti"))
• The % operator can also be used for string formatting
• The modulo operator % is overloaded by the string
class to perform string formatting. Therefore, it is
often called string modulo (or sometimes even called
modulus) operator.
• # print integer and float value
print(“St.Mary’s : % 2d, College : % 5.2f" %(1, 05.333))
• # print integer value
print("Total students : % 3d, Boys : % 2d" %(240, 120))
eval()
• a built-in- function used in python
• eval function parses the expression argument
and evaluates it as a python expression.
• the eval function evaluates the “String” like a
python expression and returns the result as
an integer.
• Syntax:
eval(expression, [globals[, locals= None]])
• The arguments or parameters of eval() are strings
• Also global and locals can be used as an argument
inside eval()
• Globals must be represented as a dictionary and
the locals as a mapped object.
• The return value would be the result of the
evaluated expression. Usually the return type is an
integer.
input = input("Enter any number of your choice:")
print(input)
print(type(input))
-------------------------------------------------------------------
- Enter any number of your choice: 10 + 10
10 + 10
<class 'str'>
eval = eval(input("Enter any number of your choice"))
print(eval)
print(type(eval))
--------------------------------------------------------------------
Enter any number of your choice: 10 + 10
20
<class 'int'>
• eval function is mostly used in situations or
applications which need to evaluate
mathematical expressions.
• Also if the user wants to evaluate the string
into code then can use eval function, because
eval function evaluates the string expression
and returns the integer as a result.
• The input() takes the user input, but when the
user enters an integer as an input the input()
returns a string, but in the case of eval() it will
evaluate the returned value from a string to an
integer.
print(eval(“5==5”))
print(eval(“4<10”))
print(eval(“8+4-2*3”))
print(eval(“ ‘py’ *5”))
print(eval(“10 **2”))
print(eval(“ ‘hello’ + ‘py’ ”))
o/p
True
True
6
py py py py py
100
hellopy
We can use eval() to execute functions, call
methods, reference variable etc.
print(eval(“abs(-11)”))
print(eval(‘ “hello”.upper()’ ))
x=2
print(eval(“x+4”))
o/p
11
HELLO
6
eval() only works with an expression
>>>eval(‘a=1’)
This causes an error
evaluate = input(“Enter what operation x has to perform: “)
print(evaluate)
print(type(evaluate))
--------------------------------------------------------------------
Enter what operation x has to perform: x + x + 100 - 35 + 5 * 80
x + x + 100 - 35 + 5 * 80
<class 'str'>
x = 10
print(type(x))
<class 'int'>
expression = eval(evaluate)
print(expression)
print(type(expression))
--------------------------------------------------------------------
485
<class 'int'>
• The second argument to eval() is called globals.
It’s optional and holds a dictionary that provides a
global namespace to eval(). With globals, you can
tell eval() which global names to use while
evaluating expression.
• Global names are all those names that are
available in your current global scope or
namespace. You can access them from anywhere
in your code.
• All the names passed to globals in a dictionary will
be available to eval() at execution time.
• You can insert names into globals by listing
them in your dictionary, and then those names
will be available during the evaluation process.
• You can also supply names that don’t exist in
your current global scope
• Even though z isn’t defined in your current
global scope, the variable is present
in globals with a value of 300. In this
case, eval() has access to z as though it were a
global variable.
• Python’s eval() takes a third argument
called locals. This is another optional
argument that holds a dictionary. In this case,
the dictionary contains the variables
that eval() uses as local names when
evaluating expression.
• Local names are those names (variables,
functions, classes, and so on) that you define
inside a given function. Local names are visible
only from inside the enclosing function. You
define these kinds of names when you’re
writing a function.
UNIT 2
• A programs control flow is the order in which
the programs code executes.
• A control statement is a statement that
determines the control flow of a set of
instructions.
• 3 types
• Sequential control
• Selection control
• Iterative control
• Sequential control - instructions are executed
in the order that is written.
• Selection control - selectively executes
instructions
• Iterative control- repeatedly executes
instructions based on condition
BOOLEAN EXPRESSIONS
• Expression that evaluates to True or False
• It has only two values; True or False.
>>>5==5
True
>>>5==6
False
>>>True
True
>>>False
False
Boolean expressions are used to denote the
conditions for selection and iterative control
statements.
The comparison operators are
==
!=
<
>
<=
>=
The comparison depends on the type of the
objects.
x=5
y=8 Output
print(“x==y:”,x==y) x==y: False
x!=y: True
print(“x!=y:”,x!=y) x<y: True
print(“x<y:”,x<y) x>y: False
print(“x>y:”,x>y) x>=y: False
x<=y: True
print(“x>=y:”,x>=y)
print(“x<=y:”,x<=y)
Strings can also be used with comparison
operators. They are case-sensitive
msg1=”Welcome”
msg2=”welcome”
print(“Is message1=message2:”,msg1==msg2)
Output
Is message1=message2: False
Compound Boolean Expression
Simple logical expressions can be chained with
logical or boolean operators like and,or,not to
form complex compound expressions.
and True if both operands are True
or True if at least one operand is True
not True only if false
S
CONDITIONAL STATEMENTS
• They are statements which are associated with some conditions.
• The condition usually uses comparison or arithmetic expressions
with variables .
• These expressions give boolean values.
• The boolean expression after the if statement is called the
condition.
• Syntax:
>>>if boolean expression:
statements
print
• The set of intended statements following the
conditional statements is called the block.
• Indentation can be done with tabs or spaces
usually four spaces.
• The first unintended statement is the end of
the block.
• The statement block inside the compound
statement is called the body of the statement.
• An if statement can have any number of
statements inside the body with at least one
statement.
SIMPLE IF STATEMENT
• It is known as a decision making statement.
• There is a condition in the if clause
• If the condition is true, the block of statement will be executed, otherwise
not.
• A colon(:) must follow the expression.
• The exp can be enclosed in parentheses.
• Statements is a block of one or more statements to be executed if the
condition is True.
Syntax :
>>>if expression:
statements
• The statements within a block must all be
intended to the same number of spaces from
the left.
• The block within an if statement is called the
body of the if statement.
•
Flow Chart for Simple if
Example
Statement
var = 200
if ( var == 100 ) :
print "Value of expression is 100
print “Let’s Continue with program!"
Example
num=int(input(“enter a number”))
If (num%2==0)
print(num,”is even”)
(EXPLAIN)
if (x<10):
y=x
Same can be written as
if (x<10): y=x
In the same line as the if statement as the body
contains only one statement.
if (x<10):
y=x
No indentation.Produces error
• A decision can be base on any exp.
• If an exp evaluates to zero, it is treated as
False
• If an exp evaluates to a nonzero value,it is
treated as True
• A non zero number,non empty string,
tuple,list,dictionary evaluates as True
• Zero,None and empty strings,tuples,
lists,dictionary evaluate as False
If x:
SIMPLE IF STATEMENT
• It is known as a decision making statement.
• There is a condition in the if clause
• If the condition is true, the block of statement
will be executed, otherwise not.
Syntax :
>>>if expression:
Statement block1
else :
Statement block2
• An else statement can be combined with an if
statement.
• It contains a block of code which is executed if
the conditional expression associated with if is
false.
• Else is optional.
• Example :
>>>var=100
if (var==100):
print “value of expression is 100”
Header and Suite(body) and clause page 84
Flowchart for if-else
Example
if x % 2 == 0:
print(x, " is even.")
else:
print(x, " is odd.")
if(cond):
statement1
statement2
else:
statement1 These are valid
statement2
if(cond):
statement1
statement2
else:
statement1
statement2
if(cond):
statement1
statement2
else:
statement1 These are invalid
statement2
if(cond):
statement1
statement2
else:
statement1
statement2
if a>b:
max=a
else:
max=b
Can be expressed using conditional exp of the form
exp1 if cond else exp2
exp1 is the value of the conditional exp if condition is
True
Cond is a Boolean exp which appears in the if statement
exp2 is the value of the conditional exp if condition is
False
max=a if a>b else b
Largest of three numbers
a=int(Input(“Enter the first number”))
b=int(Input(“Enter the second number”))
c=int(Input(“Enter the third number”))
big=a if a>b else b
big=big if big>c else c
print(big,”is bigger among”,a,b,c)
MULTIWAY STATEMENT(if-elif-else)
Sometimes there are more than two possibilities and we need more
than two branches.
if choice == "a":
function_one()
elif choice == "b":
function_two()
elif choice == "c":
function_three()
else:
print("Invalid choice.")
If-elif-else
• Multiple expressions can be checked with the help of elif
statements and execute the corresponding block of code
along with the associated elif statement if condition is true.
• Elif statement is optional.
• There can be multiple elif following an if.
• Syntax:
>>>if expression1:
statement1
elif expression2:
statement2
elif expression3:
statement3
else expression4:
statement4
Python executes only one block in an if-elif-else
Chain.
colour=input(“enter choice of colour from VIBYOR”)
if(colour==’V’ or colour==’v’):
print(“You selected violet”)
elif(colour==’I’ or colour==’i’):
print(“You selected Indigo”)
elif(colour==’B’ or colour==’b’):
print(“You selected Blue”)
elif(colour==’G’ or colour==’g’):
print(“You selected Green”)
elif(colour==’Y’ or colour==’y’):
print(“You selected Yellow”)
elif(colour==’O’ or colour==’o’):
print(“You selected Orange”)
elif(colour==’R’ or colour==’r’):
print(“You selected Red”)
else:
print(“Invalid Choice”)
Nesting in if statement
• There may be a situation when you want to
check for another condition after a condition
resolves to true. In such a situation, you can
use the nested if construct.
• In a nested if construct, you can have an
if...elif...else construct inside
another if...elif...else construct.
Syntax
if expression1: statement(s)
if expression2: statement(s)
elif expression3: statement(s)
elif expression4: statement(s)
else: statement(s)
else: statement(s)
Example
var = 100
if var < 200: print "Expression value is less than 200"
if var == 150: print "Which is 150"
elif var == 100: print "Which is 100"
elif var == 50: print "Which is 50"
elif var < 50: print "Expression value is less than
50“
else:
print "Could not find true expression“
print "Good bye!"
Example Flow Chart
if x < y: STATEMENTS_A
else:
if x > y: STATEMENTS_B
else: STATEMENTS_C
Control statements(Iterative Control)
Iteration is the process of executing the same block of code over and
over,potentially many times.
A programming structure that implements iteration is called a loop
An iterative control statement is a control statement providing the repeated
execution of a set of instructions.
2 types of iteration: indefinite and definite
In indefinite iteration, the number of times the loop is executed is not
specified explicitly in advance.The block is executed as long as
some condition is met.
In definite iteration, the number of times the loop is executed is
specified explicitly at the time the loop starts.
The iterative control statements are:
For
While
Range
for statement
• for loop is an iterator based loop
• It goes through the elements in any ordered
sequence list i.e., in strings, lists, tuples, the keys
of the dictionary and other variables
• In each iteration step, a loop variable is set to a
value.
Syntax:
>>> for x in y: for (i=0;i<n;i++)
Block 1 printf(“%d”, i)
else:
Block 2
• With the for loop we can execute a set of
statements, once for each item in a list, tuple,
set etc.
• The for loop does not require an indexing
variable to set beforehand.
• The else clause executes after the loop
completes normally. This means that the loop
did not encounter a break statement.
>>>fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
>>> for letter in ‘Python’ :
print(‘Current letter :’ , letter)
>>>subjects=[‘maths’, ’physics’, ‘chemistry’,
‘computer’]
for x in subjects:
print(x)
Range function
• range() is a built in function in Python that helps
us to iterate over a sequence of numbers .
• It produces an iterator that follows arithmetic
progression
syntax:
range(start, stop, step)
start Optional. An integer number specifying at
which position to start. Default is 0
stop Mandatory. An integer number specifying at
which position to stop (not included).
step Optional. An integer number specifying the
incrementation. Default is 1
>>>x = range(6)
>>> x = range(3, 6)
for n in x: for n in x:
print(n) print(n)
>>>x= range(2,10,2)
for n in x:
... print(n)
...
2
4
6
8
>>> for x in range(7):
print(x)
else:
print(‘HOW ARE YOU’)
0
1
2
3
4
5
6
HOW ARE YOU
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n/x)
break
4 equals 2 * 2.0
6 equals 2 * 3.0
8 equals 2 * 4.0
9 equals 3 * 3.0
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
4 equals 2 * 2.0
6 equals 2 * 3.0
8 equals 2 * 4.0
9 equals 3 * 3.0
9 is a prime number
(The else block just after for/while is executed only when the loop is NOT
terminated by a break statement.)
>>> subjects=[‘maths’, ’physics’, ‘chemistry’,
‘computer’]
>>> for index in range(len(subjects)):
print(‘current subject:’ ,subjects[index])
Current subject: maths
Current subject: physics
Current subject: chemistry
Current subject: computer
while loop
• while loop executes a set of statements as long as a
condition is true.
• It is an iterative statement
syntax
while condition:
statement(s)
next statement
• Here, statement(s) may be a single statement or a block of
statements. The condition may be any expression, and true
is any non-zero value. The loop iterates while the condition
is true.
• When the condition becomes false, program control passes
to the line immediately following the loop.
• Sometimes a while loop will never execute.
When the condition is tested and the result is
false, the loop body will be skipped and the
first statement after the while loop will be
executed.
Flow Chart
The count is: 0
count = 0
while (count < 9): The count is: 1
print ('The count is:', count) The count is: 2
count = count + 1 The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
• Same as with for loops, while loops can also
have an optional else block.
• The else part is executed if the condition in
the while loop evaluates to False and if the
condition is also false.
• The while loop can be terminated with a break
statement. In such cases, the else part is
ignored. Hence, a while loop's else part runs if
no break occurs and the condition is false.
Program Code Output
count = 0 Inside loop
while count < 3: Inside loop
print("Inside loop") Inside loop
count = count + 1 Inside else
else:
print("Inside else")
break statement
• Normally used with for and while loops
• On encountering the break statement,
execution is transferred to the statement that
is immediately following the loop
• The break statement terminates the loop
containing it.
Syntax:
break
Flow Chart for the break statement
Program code output
# Use of break statement s
inside the loop t
for val in "string": r
if val == "i": The end
break
print(val)
print("The end")
continue statement
• The continue statement is used to skip the rest
of the code inside a loop for the current
iteration only.
• Loop does not terminate but continues on
with the next iteration.
Flowchart for the continue statement
Program code output
# Program to show the use s
of continue statement t
inside loops r
for val in "string": n
if val == "i": g
continue The end
print(val)
print("The end")
Program code output
# Print first four even 2
numbers 4
for i in range(1,10): 6
if i%2!=0 8
continue
print(val)
print("The end")
Nested Loops
• Python programming language allows to use
one loop inside another loop
• The "inner loop" will be executed one time for
each iteration of the "outer loop"
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
while expression:
while expression:
statement(s)
statement(s)
• a for loop can be inside a while loop or vice
versa
Program
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana","cherry"]
for x in adj:
for y in fruits:
print(x, y)
Output
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
22
333
4444
Infinite Loops
• A loop becomes infinite loop if a condition
never becomes FALSE in a while loop.
• This results in a loop that never ends. Such a
loop is called an infinite loop.
while True:
print("hello world")
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
#var=var+1
print "Good bye!“
the loop gets executed forever
current_number = 1
while current_number <= 5:
print(current_number)
current_number = current_number +1
UNIT 3
• Functions
• Built-in functions
• Mathematical functions
• Date time functions
• Random numbers
• Writing user defined functions
• Composition of functions
• Parameters and arguments
• Default parameters
• Function calls
• Return statement
• Using global variables
• Recursion
Functions
• Functions are self contained programs that
perform some particular tasks
• Once a function is created by the prgmmer for
a specific task, the function can be called
anytime to perform that task
• Suppose, we want to perform a task several
times ,instead of writing code for that
particular task repeatedly, we create a
function for that task and call it when we want
to perform the task.
• Each function is given a name, which can be
used to called the function whenever needed.
• A function may or may not return a value.
• There are two types of functions
❖ Built-in functions
❖ User defined functions
Advantages of using functions
• Functions help break our program into smaller
and modular chunks. As our program grows
larger and larger, functions make it more
organized and manageable.
• It avoids repetition or duplication of code.
• Makes the code reusable.
• Helps improving the clarity of the code
Built-in Functions
• These are functions already defined in the Python
Programming language.
• Every built in function in Python performs some
particular task
• The built in functions can be called directly to
perform the task it was built for.
• For example, the Math module has built in
functions that perform tasks related to
Mathematics
Examples of some built-in
functions:len(),abs(),range(),float(),eval()
Type Conversion
• The process of converting a Python data
type into another data type is known as type
conversion.
• There are mainly two types of type conversion
methods in Python, namely, implicit type
conversion and explicit type conversion
• In Implicit type conversion, Python automatically
converts one data type to another data type. This
process doesn't need any user involvement.
• When the data type conversion takes place during
compilation or during the run time, then it is
called an implicit data type conversion.
Python handles the implicit data type conversion,
so we do not have to explicitly convert the data
type into another data type
• Python always converts smaller data type into
larger data type to prevent the loss of data.
• Implicit conversion is also known as Type Coercion
and it is automatically done by the interpreter.
>>> a=5
>>> b=5.5 >>> minute=59
>>> sum= a+b >>> float(minute)/60
>>> print(sum) 0.9833333333333333
10.5 >>> minute=59
>>> print(type(sum)) >>> minute/60.0
<class 'float'> 0.9833333333333333
>>> >>>
• Explicit type conversion is also known as type
casting. Explicit type conversion takes place when
the programmer clearly and explicitly defines the
same in the program. For explicit type conversion,
there are some in-built Python functions
• There are some built in function in Python
programming language that can convert one type
of data into another type. For example, int() and
float().
syntax
(required_data type)(expression)
>>> int(5.5) • In the second case, we
5 took a string that was not
a number and applied the
>>> int('Python')
int() to it, but got an
Traceback (most recent call error.
last):
• This means a string that is
File "<stdin>", line 1, in not a number cannot be
<module> converted to an integer.
ValueError: invalid literal for • But in the third case, we
int() with base 10: took a number as a string
'Python' and applied the int() to it
>>> int('5') and we got the integer
5 corresponding to it.
>>> float(45)
45.0
>>> float('5')
5.0
>>>
>>> str(67)
'67'
>>> print('Python Version'+ 3.7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "float") to str
>>> print('Python Version'+ str(3.7))
Python Version3.7
>>> a=100
>>> b='200'
>>> sum1=a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> sum2=a + int(b)
>>> print(sum2)
300
>>>
Mathematical Functions
• The math module in Python is used to access
mathematical functions in the Python.
• A module is a file that contains some
predefined Python codes.
• A module can define functions, classes and
variables.
• It is a collection of related functions grouped
together.
• Before using a module in Python, we have to
import it.
Example:
>>> import math
• This statement creates an object of module
named math.
• There are many predefined functions and
variables that reside under the module object.
• To access these functions, we have to write
the name of the module followed by a dot (.)
followed by the function name.
>>> angle = 2.5
>>> height = math.sin(angle)
>>> print(height)
0.5984721441039564
>>>
>>> degree = 45
>>> angle = degree * 2 * math.pi/360.0
>>> math.cos(angle)
0.7071067811865476
>>>
Date and Time Functions
• Python provides built in modules for time and
calender for handling date and time.
• We need to import the time module and the
calendar module to use the time and date
respectively.
import time;
localtime = time.localtime(time.time())
print "Local current time :", localtime
This would produce the following result, which could be
formatted in any other presentable form
Output:
Local current time : time.struct_time(tm_year=2020, tm_mon=8, tm_mday=2,
tm_hour=20, tm_min=53, tm_sec=48, tm_wday=6, tm_yday=215, tm_isdst=0)
You can format any time as per your requirement, but
simple method to get time in readable format is asctime()
import time;
localtime = time.asctime( time.localtime(time.time()) )
print "Local current time :", localtime
Output:
Local current time : Sun Aug 2 20:55:55 2020
time()
Localtime()
Acstime()
The calendar module gives a wide range of methods to play
with yearly and monthly calendars
import calendar
cal = calendar . month(2020, 3)
print "Here is the calendar:" cal
Output:
Here is the calendar: March 2020
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Random Numbers
• Python can generate random numbers by
using the random module.
import random Output:
n = random.random()
print(n) 0.8698683312930156
The random() method in random module generates a float number between 0 and 1.
The randint() method generates a integer between a given range of numbers.
import random Output:
n = random.randint(0,22)
print(n) 12
We can use the above randint() method along with a for loop to generate a list
of numbers. We first create an empty list and then append the random numbers
generated to the empty list one by one.
import random Output:
randomlist = [] [29, 18, 30, 1, 15]
for i in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)
We can also use the sample() method available in random module to directly
generate a list of random numbers. Here we specify a range and give how many
random numbers we need to generate.
import random Output:
#Generate 5 random numbers between 10 and 30
randomlist = random.sample(range(10, 30), 5) [16, 19, 13, 18, 15]
print(randomlist)
Writing User Defined Functions
• Python allows users to define their own
functions
• For this the function has to be defined.
• Function definition:
Here the user has to define a name for the
new function and also the body of the
function that will be executed when the
function is called.
• The block of the function starts with the keyword def
followed by the function-name.
def sumofnumbers (num1,40):
statements
return
Statement after function definition
• The input values or the function parameters are given
in parentheses following the function-name.
• The block of statements starts from a colon
• The block is ended with a return statement
• The function may or may not return a value
• If more than one value is to be returned, then separate
the values using commas.
• The default return value is NONE.
Syntax of function def functionname( parameters ) :
“”"function_docstring“””
function_statements
return [expression]
• A docstring is a string literal which is used to
document a specific part of code.
• It is used like comments in programming
languages.
• It does not affect the program execution.
• The first line of the function definition is called the
header of the function,
• The header line is followed by a colon
• The rest of the function is called the body of the
function
• When a function definition is executed, a function
object is created.
• The statements in the function body gets
executed only when the function is called.
• Outputs are generated only by the function calls
and not by the function definition.
def greet(name):
"""
This function greets
to the person passed
in as a parameter
"""
print("Hello, " + name + ". Good morning!")
Once we have defined a function, we can call it from another function, program or
even the Python prompt. To call a function we simply type the function name with
appropriate parameters.
>>> greet('Paul')
Output Hello, Paul. Good morning!
>>>print(greet.__doc__)
This function greets
to the person passed
in as a parameter
Parameters and arguments
• Parameters and arguments are values or expressions
passed to the functions between parenthesis.
• Many of the built in functions also need arguments to
be passed to them
math.sqrt(25)
• At the time of function defintion we have to define
some parameters, if that function requires some
arguments to be passed at the time of calling.
• The value of argument is always assigned to a variable
known as parameter.
• There are 4 types of formal arguments using
which a function can be called.
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
• Required arguments are the arguments passed to
a function in correct positional order.
• Here, the number of arguments in the function
call should match exactly with the function
definition.
• Thus, required arguments are the mandatory
arguments of a function. These argument values
must be passed in correct number and order
during function call.
>>>def printme( str):
"This prints a passed string into this function“
print str
return;
To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error.
>>> printme()
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Default arguments
• A default argument is an argument that
assumes a default value if a value is not
provided in the function call for that
argument.
• If we do not provide a value to the parameter
at the time of calling, it will not produce an
error. Instead it will pick the default value and
use it.
>>>def printinfo( name, age = 35 ):
"This prints a passed info into this function“
print "Name: ", name
print "Age ", age
return;
>>>printinfo(‘Paul’,45)
>>>printinfo(35,”paul’)
>>>printinfo( age=50, name=“Paul" )
Name: Paul
Age 50
>>>printinfo(age=25)
>>>printinfo( name=“Paul" )
Name: Paul
Age 35
Variable-length arguments
• You may need to process a function for more
arguments than you specified while defining the
function.
• These arguments are called variable-length arguments
• The arguments are not named in the function
definition, unlike required and default arguments.
• An asterisk (*) is placed before the variable name that
holds the values of all non keyword variable
arguments.
• This tuple remains empty if no additional arguments
are specified during the function call.
Syntax: def functionname([formal_args,] *var_args_tuple ):
"function_docstring“
function_statements
return [expression]
Example:
>>>def printinfo( arg1, *vartuple ): >>>printinfo( 10 )
"This prints a variable passed arguments" Output is:
print "Output is: " 10
print arg1
for var in vartuple:
print var
>>>printinfo( 70, 60, 50,30,20 )
return;
Output is:
70
60
50
30
Keyword arguments
• Keyword arguments are related to the
function calls. When you use keyword
arguments in a function call, the caller
identifies the arguments by the parameter
name.
• This allows you to skip arguments or place
them out of order because the Python
interpreter is able to use the keywords
provided to match the values with parameters
• You can also make keyword calls to
the printme() function in the following ways
>>>def printme( str ):
"This prints a passed string into this function“
print str
return;
>>>printme( str = "My string")
The output is
My string
>>>def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
>>>printinfo( age=50, name=“Paul" )
The output is
Name: Paul
Age 50
Function call
• Defining a function only gives it a name,
specifies the parameters that are to be
included in the function and structures the
blocks of code.
• Once the basic structure of a function is
finalized, you can execute it by calling it from
another function or directly from the Python
prompt
• A function is called using the name of the function
with which it was defined , followed by a pair of
parenthesis.
• Any input parameters or arguments are to placed
within these calling parenthesis.
• All parameters (arguments) in the Python
language are passed by reference. It means if you
change what a parameter refers to within a
function, the change also reflects back in the
calling function
>>>def printme( str ):
"This prints a passed string into this function“
print str
return;
>>>printme(‘Hello World’)
>>>printme(‘Python programming’)
Output
Hello World
Python programming
Sample C pgm for showing Pass by value and
pass by reference
Void valuechange(int *a,int *b)
{
a= a+b; a=900
b=b+20; b=820
print(a,b)
Return (a,b)
}
Void main()
{
Int a=100,b=800;
.
.
.
Valuechange(&a,&b);
>>>def changeme( mylist ):
"This changes a passed list into this function“
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
>>>mylist = [10,20,30];
>>> changeme( mylist );
>>>print "Values outside the function: ", mylist
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Here, we are maintaining reference of the passed object and appending values in
the same object.
>>>def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assign new reference in mylist
print "Values inside the function: ", mylist
return
>>>mylist = [10,20,30];
>>> changeme( mylist );
>>>print "Values outside the function: ", mylist
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Here argument is being passed by reference and the reference is
being overwritten inside the called function
Return statement
• The return statement is used to exit a function.
• A function may or may not return a value
• If a function returns a value,it is passed back by
the return statement as argument to the caller.
• If it does not return a value, we can simply write a
return statement with no arguments.
return [expression]
>>>def sum( arg1, arg2 ):
# Add both the parameters and return them.“
total = arg1 + arg2
print "Inside the function : ", total
return total;
Output
Inside the function : 30
Outside the function : 30
Scope of Variables
• All variables in a program may not be accessible at
all locations in that program. This depends on
where you have declared a variable.
• The scope of a variable determines the portion of
the program where you can access a particular
identifier. There are two basic scopes of variables
in Python −
• Global variables
• Local variables
Global and Local Variables
• Variables that are defined inside a function body
have a local scope, and those defined outside
have a global scope.
• This means that local variables can be accessed
only inside the function in which they are
declared, whereas global variables can be
accessed throughout the program body by all
functions. When you call a function, the variables
declared inside it are brought into scope.
>>>total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2;
# Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
>>>sum( 10, 20 );
>>> print "Outside the function global total : ", total
Output
Inside the function local total : 30
Outside the function global total : 0
Python Recursive Function
• In Python, we know that a function can call
other functions.
• It is even possible for the function to call
itself.
• These types of construct are termed as
recursive functions.
>>>def factorial(x):
"""This is a recursive function
to find the factorial of an integer""“
if x == 1:
return 1
else:
return (x * factorial(x-1))
>>>num = 3
>>>print("The factorial of", num, "is",
factorial(num)
Output
The factorial of 3 is 6
>>>factorial(4)
24
Some programs using functions
UNIT IV
Strings
• Strings are arrays of bytes representing
Unicode characters.
• Python does not have a character data type.
• String literals in Python are surrounded by a
single or double quotes.
>>print(“Hello”)
>>print(‘Hello’)
• A string can be assigned to variable
>>> a=“Hello”
>>> b=“World”
>>> print(a,b)
• A multiline string can be assigned to variable
using three quotes (single or double)
>>> a=“”” This is an example of a long sentence
that can be assigned to a variable using three
single or double quotes”””
• Individual characters can be accessed using
indexing and a range of characters can be
accessed using slicing.
>>>a=“Hello, World!”
>>>print(a[1])
e
• Slicing
>>> b =“Hello, World!”
>>>print(b[2:5])
llo
• Errors
IndexError- when trying to access a character out of
index range
The index must be an integer exp.using other types will
result in TypeError
TypeError- index should be integer
• Python allows negative indexing. The index -1 will refer
to the last item,-2 will refer to the second last item etc.
>>> b =“Hello, World!”
>>>print(b[-5:-2])
orl
Deleting and Updating a string
• Strings are immutable
• Elements of a string cannot be changed once it
is assigned.
>>>txt= “Hello! Welcome”
>>>txt[0]=‘h’
The code generates a TypeError
TypeError: ‘str’ object does not support item
assignment
• But an existing string can be updated by
reassigning a variable to another string.
>>>txt= “Hello! Welcome”
>>>print(txt)
>>>txt=“This is a new string”
>>>print(txt)
• Deleting or removing characters from a string is
not possible
• But an entire string can be deleted using the
keyword del
• del is used to delete objects
• In Python everything is an object. So del can be
used to delete variables, lists, parts of lists etc
>>>txt= “Hello! Welcome”
>>>print(txt)
>>>del txt
>>>print(txt) NameError: name ‘txt’ is not defined
Escape Characters
• To insert characters that have predefined meaning like the
single quote, double quote etc, we use the escape
character.
• An escape character is a backslash(\) followed by the
character that has to be inserted.
• Thus, escape sequences allow including special characters
to be inserted in a string.
>>> txt= “Type “End” to terminate the input”
This causes an error.
To insert use the escape character \”
>>> txt= “Type \“End \” to terminate the input”
\\ Backslash
\’ Single quote
\t Horizontal tab
\v Vertical tab
\n Linefeed
\b Backspace
String Special Operators
>>>a= ‘Hello’
>>>b=‘Python’
+ Concatenation a+b
HelloPython
* Repetition a*2
HelloHello
[] Slice a[1]
e
[:] Range Slice a[1:4]
ell
in Membership H in a
Returns true is the character 1
exists in the string
not in Membership M not in a
Returns true if a character 1
does not exist in the string
r/R Raw string Print(r’\n’)
Suppresses actual meaning \n
of escape characters
% Used for formatting the
string
>>>txt= “This sample text is used to check a phrase”
>>>x = “ext” in txt
>>>print(x)
True
>>>txt= “This sample text is used to check a phrase”
>>>x = “ext” not in txt
>>>print(x)
False
• The built function len() is used to find the length of the string.
>>> a= “Hello, World!”
>>> print(len(a))
13 size = len(var)
String Formatting Operator
• % is used as the string formatting operator.
Eg:
>>> print(“My name is %s and I am %d years
old” %(Raju, 24))
My name is Raju and I am 24 years old
%c Character
%s String conversion
%d Signed decimal integer
%i Signed decimal integer
%u Unsigned decimal integer
%o Octal integer
%x Hexadecimal integer lowercase
%X Hexadecimal integer uppercase
%e Exponential notation with lower
case e
%E Exponential notation with upper
case E
%f Floating point real number
Built-in String methods
• Python has several built in methods that can
be used with strings.
• All string methods return new values.
• They do not change the original string
capitalize()
the first character changed to uppercase
Syntax:
string.capitalize()
>>>txt= “ hello, welcome to my world!”
>>> x= txt.capitalize()
>>>print(x)
casefold()
Returns a string where all the characters are
lowercase. Similar to lower()
>>>txt= “ Hello, welcome to my world!”
>>> x= txt.casefold()
>>>print(x)
center()
Will center align the string using a specified character as
the fill character. The fill character is “ “.
Syntax:
string.center(length, character)
length - required which is the length of the returned
string
character – Optional. The character to fill the missing
spaces on either side. Default is “ “
>>> txt = ‘banana’
>>> x = txt.center(20)
>>>print(txt)
count()
Returns the number of times the specified string
appears in the string
Syntax:
string.count(value,start,end)
value – required string to be searched.
start – optional. An integer. The position to start
the search. Default is 0
end- Optional. An integer. The position to end
the search. Default is end of the string.
>>> txt = “I love apples, apple is my favourite
fruit”
>>> x = txt. count(“apple”, 10, 24)
>>> print(x)
1
endswith()
Returns True if the string ends with a specified value
else returns false.
Syntax:
string. endswith( value, start, end)
value – required. The value to check if the string
ends with.
start – Optional. An integer specifying the position
where the search starts.
end - Optional. An integer specifying the position
where the search ends.
>>> txt = “ Hello, welcome to my world!”
>>> x = txt. endswith (“ ! ”)
>>> print(x)
True
expandtabs()
Sets the tabsize to a specified number of whitespaces.
Syntax:
string.expandtabs(tabsize)
tabsize – Optional. A number specifying the tabsize.
Default is 8
>>> txt = “H\te\tl\tl\to”
>>>x = txt.expandtabs(2))
>>>print(x)
H e l l o
find()
Finds the first occurrence of the specified value.
Returns -1 if value not found.
Similar to the index(). But index() raises an exception
if the value is not found.
Syntax:
string. find(value, start, end)
value- Required. The value to search for.
start – Optional. Where to start the search. Default
is 0.
end – Optional. Where to end the search. Default is
the end of the string
>>> txt = “ Hello, welcome to my world!”
>>> x = txt. find(“ welcome ”)
>>> print(x)
7
index()
Finds the first occurrence of the specified value.
Raises an exception if the value is not found.
Syntax:
string. index(value, start, end)
value- Required. The value to search for.
start – Optional. Where to start the search.
Default is 0.
end – Optional. Where to end the search.
Default is the end of the string.
>>> txt = “ Hello, welcome to my world!”
>>> x = txt. index(“ Welcome ”)
>>> print(x)
ValueError
isalnum()
Returns True if all the characters are alphanumeric ie
a-z and 0-9
Syntax:
string.isalnum()
>>>txt = “Company12”
>>>x= txt.isalnum()
>>>print(x)
True
isalpha()
Returns True if all the characters are alphabets i.e,
a-z
Syntax:
string.isalpha()
>>>txt = “CompanyX”
>>>x= txt.isalpha()
>>>print(x)
True
isdigit()
Returns True if all characters are digits else False.
Syntax:
string.isdigit()
>>>txt = “5088”
>>>x= txt.isdigit()
>>>print(x)
True
isidentifier()
Returns True if the string is a valid identifier. Otherwise
False.
Alphanumeric characters or underscores. Cannot start
with a number or have spaces.
Syntax:
string.isidentifier()
>>>txt = “Demo12”
>>>x= txt.isidentifier()
>>>print(x)
True
islower()
Returns True if all characters are in lowercase.
Numbers, symbols and spaces are not checked. Only alphabet
characters are checked.
Syntax:
string.islower()
>>>txt = “hello world !”
>>>x= txt.islower()
>>>print(x)
True
isnumeric()
Returns True if all characters are numeric 0-9 .
Syntax:
string.isnumeric()
>>>txt = “45324”
>>>x= txt.isnumeric()
>>>print(x)
True
isspace()
Returns True if all characters in the string are
whitespaces.
Syntax:
string.isspace()
>>>txt = “ ”
>>>x= txt.isspace()
>>>print(x)
True
istitle()
Returns True if all words in a text start with a uppercase letter
and the rest of the word are lowercase letters. Symbols and
numbers are ignored.
Syntax:
string.istitle()
>>>txt = “ Hello, And Welcome To My World! ”
>>>x= txt.istitle()
>>>print(x)
True
title()
Returns a string where the first character in every word
is uppercase letter and the rest of the word are
lowercase letters. Symbols and numbers are ignored.
Syntax:
string.title()
>>>txt = “ Hello, and welcome to my World! ”
>>>x= txt.title()
>>>print(x)
Hello, And Welcome To My World!
isupper()
Returns True if all characters are in uppercase.
Numbers, symbols and spaces are not checked. Only
alphabet characters are checked.
Syntax:
string.isupper()
>>>txt = “HELLO,WORLD!”
>>>x= txt.isupper()
>>>print(x)
True
join()
Takes all items in an iterable and joins them into one
string. A separator string is also specified.
Syntax:
string.join(iterable)
>>>myTuple = (“John”, “ Mathew”, “Paul”)
>>>x= ‘#’.join(myTuple)
>>>print(x)
John#Mathew#Paul
lower()
Returns a string where all the characters are
lowercase. Symbols and numbers are ignored.
Syntax:
string.lower()
>>>txt = “Hello my FRIENDS”
>>>x= txt.lower()
>>>print(x)
hello my friends
upper()
Returns a string where all the characters are
uppercase. Symbols and numbers are ignored.
Syntax:
string.upper()
>>>txt = “Hello my FRIENDS”
>>>x= txt.upper()
>>>print(x)
HELLO MY FRIENDS
swapcase()
Returns a string where all the uppercase letters are
lowercase and vice versa. Symbols and numbers are
ignored.
Syntax:
string.swapcase()
>>>txt = “Hello my FRIENDS”
>>>x= txt.swapcase()
>>>print(x)
hELLO MY friends
split()
Splits a string into list . The separator can be specified, default is any
whitespace. When maxsplit is specified ,the list will contain the specified
number of elements plus one.
Syntax:
string.split(seperator, maxsplit)
seperator – Optional. Specifies the separator to use when splitting the string .
Default separator is blank space.
maxsplit - Optional. Specifies how many splits to do. Default is -1, which is all
occurrences.
>>>txt = “Thank you for the music”
>>>x= txt.split()
>>>print(x)
[‘Thank ‘ , ‘you’ , ‘ for’ , ‘the’ , ‘music’ ]
rsplit()
Splits a string into list starting from the right . If no max is specified, this method will
return same as the split(). The separator can be specified, default is any whitespace.
When maxsplit is specified ,the list will contain the specified number of elements
plus one.
Syntax:
string.rsplit(seperator, maxsplit)
seperator – Optional. Specifies the separator to use when splitting the string . Default is
separator.
maxsplit - Optional. Specifies how many splits to do. Default is -1, which is all
occurrences.
>>>txt = “apple, banana, cherry”
>>>x= txt.rsplit(“, “)
>>>print(x)
[‘apple‘ , ‘banana’ , ‘ cherry’ ]
splitlines()
Splits a string into list . The split is done at the line breaks.
Syntax:
string.splitlines(keeplinebreaks)
keeplinebreaks – Optional. Specifies if the line breaks should
be included (True) , or not (False). Default is False.
>>>txt = “Thank you for the music\n And the songs you gave”
>>>x= txt.splitlines()
>>>print(x)
[‘Thank you for the music’ , ‘ And the songs you gave’ ]
startswith()
Returns True if the string starts with the specified value else False.
Syntax:
string . startswith ( value, start, end)
value - Required. The value to check if the string starts with.
start – Optional. An integer specifying at which position to start the
search.
end – Optional. An integer specifying at which position to end the
search.
>>>txt = “Hello , Welcome to my World!”
>>>x= txt.startswith(“Hello”)
>>>print(x)
True
strip()
Removes any leading and trailing characters
Syntax:
string . strip ( characters)
characters – Optional. A set of characters to remove as leading
/trailing characters.
>>>txt = “ banana “
>>>x= txt.strip( )
>>>print(“Of all the fruits”, x , “is my favourite”)
Of all the fruits banana is my favourite
lstrip()
Removes any leading characters.
Syntax:
string . lstrip ( characters)
characters – Optional. A set of characters to remove as leading
characters.
>>>txt = “ banana “
>>>x= txt.lstrip( )
>>>print(“Of all the fruits”, x , “is my favourite”)
Of all the fruits banana is my favourite
rstrip()
Removes any trailing characters.
Syntax:
string . rstrip ( characters)
characters – Optional. A set of characters to remove as trailing
characters.
>>>txt = “ banana “
>>>x= txt.rstrip( )
>>>print(“Of all the fruits”, x , “is my favourite”)
Of all the fruits banana is my favourite
format()
Formats the specified values and insert them inside the strings
placeholders. The placeholders is defined using curly
brackets. The format() returns the formatted string.
Syntax:
string . format ( value1, value2......)
value1 , value2...... – Required. One or more values that should
be formatted and inserted in the string. The values can be a
number specifying the position of the element you want to
remove. The values are either a list separated by commas, a
key = value list, or a combination of both. The values can be
of any data type.
The placeholders can be identified using named indexes
{price}, numbered indexes {0}, or empty placeholders.
Inside the placeholders formatting type can be added to
format the result.
:+ Use a plus sign to indicate if the result is positive or
negative
:- Use a minus sign for negative values only.
:d Decimal format
:e Scientific format with a lower case e
:E Scientific format with a uppercase E
:f Fix point number format
:n Number format
:% Percentage format
partition()
Searches for a specified string and splits the string into a tuple
containing 3 elements. The first element contains the part before
the specified string. The second element contains the specified
string. The third element contains the part after the specified
string.
Syntax:
string.partition(value)
value – Required. The string to search for.
>>>txt = “ I could eat bananas all day”
>>> x = txt.partition(“bananas”)
>>>print(x)
(‘ I could eat’ , ‘bananas’, ‘all day’)
replace()
Replaces all occurrences of a specified phrase with another specified
phrase.
Syntax:
string.replace(oldvalue, newvalue, count)
oldvalue – Required. The string to search for.
newvalue - Required. The string to replace the old value with
count – Optional. A number specifying how many occurrences of the
old value is to be replaced. Default is all occurrences.
>>>txt = “ I could eat bananas all day”
>>> x = txt.replace(“bananas”, “apples”)
>>>print(x)
I could eat apples all day
rfind()
Finds the last occurrence of the specified value. Returns a value -1 if
the specified value is not found. Similar to rindex().
Syntax:
string.rfind(value, start, end)
value – Required. The value to search for.
start - Optional. Where to start the search. Default is 0.
end – Optional. Where to end the search. Default is the end of the
string.
>>> txt= "Mi casa, su casa."
>>> x= txt.rfind("casa")
>>> print(x)
12
rindex()
Finds the last occurrence of the specified value. Raises an exception if
the specified value is not found. Similar to rfind().
Syntax:
string.rindex(value, start, end)
value – Required. The value to search for.
start - Optional. Where to start the search. Default is 0.
end – Optional. Where to end the search. Default is the end of the
string.
>>> txt= "Mi casa, su casa."
>>> x= txt.rindex("casa")
>>> print(x)
12
rjust()
Will right align the string using the specified character as the fill character.
Syntax:
string.rjust(length, character)
length – Required. The length of the returned string .
character - Optional. A character to fill the missing space to the left of the
string . Default is “ “
>>> txt= “banana"
>>> x= txt.rjust(20)
>>> print(x)
>>> print(x, “ is my favourite fruit”)
banana is my favourite fruit
Python Lists
There are four data types in Python
• Lists: is a collection which is ordered and
changeable. Allows duplicate members.
• Tuple: is a collection which is ordered and
unchangeable. Allows duplicate members.
• Set: is a collection which is unordered and
unindexed. No duplicate members.
• Dictionary: is a collection which is unordered,
changeable and indexed. No duplicate members.
• Choosing the right collection type for
particular data set could mean retention of
meaning and increases efficiency and security.
List
• A list is a linear data structure where elements
have linear ordering.
• Each item in the list is identified by its index
value.
• Programming languages which begin
numbering the sequences of items with an
index value of 0 rather than 1 is referred to as
zero- based indexing.
List
• A list is a mutable, linear data structure of variable
length allowing mixed type elements, where
elements have linear ordering.ie A list need not be
homogeneous.
• Each item in the list is identified by its index value
• Programming languages which begin numbering
the sequences of items with an index value of 0
rather than 1 is referred to as zero- based
indexing.
• Python uses zero-based indexing. All lists have
index values 0....n-1, where n is the number of
elements in the list.
• An empty list is denoted by an empty pair of
square brackets [].
• Lists are denoted by comma separated list of
elements in square brackets.
[1,2,3]
[‘apples’,50, True]
Creating Lists
• A list variable can be global or local.
• A list variable should be defined before it is used
• A list is created by placing all elements inside the
square brackets separated by commas.
• It can have any number of elements and can be of
any type like integer, float,string etc.
>>> lst= [ 2, -3, 0, 4, -1 ]
>>> a= [ ]
>>> list1= [ 23.2, 4, ‘word’, [9.3, 11.2, 33.0], ‘end’]
• A list() constructor can be used to make a new
list.
>>> thislst = list( (“apple”, “banana”, “cherry”) )
>>>print(thislst)
[‘apple’, ‘banana’, ‘cherry’]
list()
>>>alist=[]
>>> for number in range(1,11):
alist+=[number]
>>> for item in alist:
print(item, end=' ')
1 2 3 4 5 6 7 8 9 10
Accessing lists using index:
• Index number which is an integer is used to access an item in the
list.
• Nested lists are accessed using nested indexing.
• If a is a list with n elements and i is an integer such that 0<=i<n,
then a[n-1] is an element in the list.
• The subscript can be specified as any integer expression.
Can be an integer literal as in a[34]
Can be an integer variable as in a[x] where x
must be an integer
Can be integer arithmetic exp as in a[x+3] where
x must be an integer
An integer result of a function call that returns an
integer as a[max(x,y)]. The function max must
return an integer
An element of another list as in a[b[3]] where b[3] must be an
integer.
Negative indexing can also be applied on list for
accessing its elements.
The index -1 refers to the last element in the list,
-2 refers to the second last element in the list
etc.
>>>thislist=[“apple”, “banana”, “cherry”]
>>>print(thislist[-1])
The action of moving through a list visiting each
element exactly once is called traversal.
• Slicing
To print a specific range of elements from the list we use
the slicing operation by specifying where to start and
where to end the range.
Syntax:
list[begin:end] list[ :]
The default value for begin is 0. A begin value less than
zero is treated as zero.
The default value of end is the end of the list . A end
value greater than the length of the list is treated as
the length of the list.
• Slicing can be used in the following ways:
a. To print elements from the beginning to a
range [ :index]
b. To print elements from the end [ :-index]
c. To print elements from specific index till the
end [index: ]
d. To print elements within a range [start : end]
e. To print whole list using slicing operation [ : ]
f. To print whole list in reverse order [ : : -1]
>>>thislist=[“apple”, “banana”, “cherry”,
”orange”, ”kiwi”, “melon”, “mango”]
>>>print(thislist[2:5])
Try other options for example.
The value of a specific item can be changed
using the index number.
>>>thislist=[“apple”, “banana”, “cherry”]
>>>thislist[1]= “orange”
>>>print(thislist)
Basic List Operations
len([1,2,3]) 3 Gives the length
[1,2,3] + [4,5,6] [1,2,3,4,5,6] Concatenation
[‘Hi!’] * 4 [‘Hi1!’, ‘Hi!’, ‘Hi!’, ‘Hi!’ ] Repitition
3 in [1,2,3] True Membership
for x in [1,2,3] : 1 2 3 Iteration
print(x)
To determine if a specified item is present in a
list
>>>thislist=[“apple”, “banana”, “cherry”]
>>>if “apple” in thislist:
print(“Yes”, ‘apple’, “ is in the fruits list”)
Adding elements to list
• append()
This method appends an element to the end of the list.
Syntax:
list.append(elmnt)
elmnt is a required keyword and can be of any data type like
string ,number,object etc.
Only one element at a time can be added using append().
For adding multiple elements using append(), loops are used.
>>> list=[]
>>> print('The initial empty list:' , list)
The initial empty list: []
>>> list.append(1)
>>> list.append(2)
>>> list.append(4)
>>> print("List after addition of 3 elements:", list)
List after addition of 3 elements: [1, 2, 4]
>>> for i in range(7,9):
list.append(i)
>>> print("the new list after appending items", list)
the new list after appending items [1, 2, 4, 7, 8]
>>> list.append((11,12))
>>> print("After appending the tuple:", list)
After appending the tuple: [1, 2, 4, 7, 8, (11, 12)]
>>> list1=[15,16]
>>> list.append(list1)
>>> print("After appending a list to the existing list:", list)
After appending a list to the existing list: [1, 2, 4, 7, 8, (11, 12), [15, 16]]
The append() method can also be used to
merge one list to another .
>>> list1=[‘a’, ’b’, ’c’]
>>list2= [1,2,3]
>>> for x in list2:
list1.append(x)
>>>print(list1)
[‘a’, ’b’, ’c’, 1, 2, 3]
• insert()
For addition of elements at the desired position insert()
method is used.
It inserts the specified value at the specified position.
Syntax:
list.insert(pos,elmnt)
pos – required and is a number specifying the position to
insert the value
elmnt –required and element of any datatype like string,
number, object etc.
>>list=[1,2,3,4]
>>> print("the initial list:", list)
the initial list: [1, 2, 3, 4]
>>> list.insert(3,12)
>>> list.insert(0,'Hello')
>>> print("List after insertion of values:",list)
List after insertion of values: ['Hello', 1, 2, 3, 12, 4]
• extend()
The extend() method adds the specified lists of elements or any
iterable to the end of the current list.
Syntax:
List.extend(iterable)
iterable – required and is any iterable like list, tuple, set etc
>>> list=[1,2,3,4]
>>> print("Initial List:",list)
Initial List: [1, 2, 3, 4]
>>> list.extend([8,'Hello','Welcome'])
>>> print("After performing the extend operation:",list)
After performing the extend operation: [1, 2, 3, 4, 8, 'Hello',
'Welcome']
Removing elements from the list
• remove()
The remove() method removes the first
occurrence of the element with the specified
value.
Syntax:
list.remove(elmnt)
elmnt - required and can be of any data type like
string,number,list etc. It is the element to be
removed from the list.
The remove() raises an error if the element is not present in the list.
The remove() method removes only a single specified item.
To remove a range of elements, iterable is used.
>>> list=[1,2,3,4,5,6,7,8,9,10]
>>> print(list)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list.remove(4)
>>> print(list)
[1, 2, 3, 5, 6, 7, 8, 9, 10]
>>> for i in range(7,10):
list.remove(i)
>>> print(list)
[1, 2, 3, 5, 6, 10]
• pop()
The pop() method removes and returns the
element at the specified position.
If the position is not specified, then the default
value of position is -1.
Syntax:
list.pop(pos)
pos-Optional and is the index number specifying
the position of the element to be removed.
The default is -1, which is the last element of
the list.
>>> list=[1,2,3,4]
>>> print(list)
[1, 2, 3, 4]
>>> list.pop()
4
>>> print(list)
[1, 2, 3]
>>> list.pop(2)
3
>>> print(list)
[1, 2]
Built-in methods and List methods
• len(list)
Gives the total length of the list
>>> list1=[1,2,3,4]
>>> list2= [1,'Hello', 'Welcome', [1,2,3]]
>>> print("list=",list1)
list= [1, 2, 3, 4]
>>> print("list2=",list2)
list2= [1, 'Hello', 'Welcome', [1, 2, 3]]
>>> print("length of list1=",len(list1))
length of list1= 4
>>> print("length of list2=",len(list2))
length of list2= 4
• max(list)
Returns item from the list with the maximum
value.
>>> list1=[1,2,3,4]
>>> print("list=",list1)
list= [1, 2, 3, 4]
>>> print("The maximum value in the list =",
max(list1))
The maximum value in the list = 4
• min(list)
Returns item from the list with the minimum
value.
>>> list1=[1,2,3,4]
>>> print("list=",list1)
list= [1, 2, 3, 4]
>>> print("The maximum value in the list =",
min(list1))
The maximum value in the list = 1
• list(seq)
Converts an iterable sequence like a string and tuple into list
>>> vowelString="aeiou"
>>> print("the vowel string is", vowelString)
the vowel string is aeiou
>>> print("converting the vowel string to list", list(vowelString))
converting the vowel string to list ['a', 'e', 'i', 'o', 'u']
>>> vowelTuple=('a', 'e', 'i', 'o', 'u')
>>> print("the tuple is", vowelTuple)
the tuple is ('a', 'e', 'i', 'o', 'u')
>>> print("converting the tuple to list", list(vowelTuple))
converting the tuple to list ['a', 'e', 'i', 'o', 'u']
• append()
• clear()
Removes all the elements from the list
>>> fruits = ["apple", "banana", "cherry"]
>>> print("Fruits=", fruits)
Fruits= ['apple', 'banana', 'cherry']
>>> fruits.clear()
>>> print("After Clear Operation, fruits=", fruits)
After Clear Operation, fruits= []
• copy()
Returns a copy of the list
>>> fruits = ["apple", "banana", "cherry"]
>>> print("Fruits=", fruits)
Fruits= ['apple', 'banana', 'cherry']
>>> x= fruits.copy()
>>> print(“x=“ x)
• count()
Returns the number of elements with the
specified value in the list
Syntax:
list.count(value)
>>> fruits = ["apple", "banana", "cherry"]
>>> print("Fruits=", fruits)
Fruits= ['apple', 'banana', 'cherry']
>>>print(“count(‘cherry’)=“,fruits.count(‘cherry’))
• extend()
• index()
returns the position of the first occurence of the
specified value
Syntax:
list.index(value)
>>> fruits = ["apple", "banana", "cherry"]
>>> print("Fruits=", fruits)
Fruits= ['apple', 'banana', 'cherry']
>>>print(“index(‘cherry’)=“,fruits.index(“cherry”))
index(‘cherry’)=2
• insert()
• remove()
• reverse()
Reverses the order of the list
Syntax:
list.reverse()
>>> fruits = ["apple", "banana", "cherry"]
>>> print("Fruits=", fruits)
Fruits= ['apple', 'banana', 'cherry']
>>>print(“index(‘cherry’)=“, fruits. index(“cherry”))
index(‘cherry’)=2
>>> fruits. reverse()
>>> print("Fruits=", fruits)
Fruits= ['cherry‘, 'banana‘, 'apple’]
>>>print(“index(‘cherry’)=“, fruits. index(“cherry”))
index(‘cherry’)=0
• sort()
Sorts the list .
Syntax:
list.sort(reverse=True/False, key=myFunc)
reverse is an optional parameter. If reverse = True then the list is
sorted in descending order. Default of reverse argument is False.
key is optional. It is a function which specifies the sorting criteria
>>> nos= [2,5,8,3,14,21]
>>> nos.sort()
>>> nos
[2, 3, 5, 8, 14, 21]
>>> nos.sort(reverse=True)
>>> nos
[21, 14, 8, 5, 3, 2]
>>> nos=['One','two','Three','Four','Five']
>>> nos
['One', 'two', 'Three', 'Four', 'Five']
>>> nos.sort()
>>> nos
['Five', 'Four', 'One', 'Three', 'two']
>>> nos.sort(reverse=True)
>>> nos
['two', 'Three', 'One', 'Four', 'Five']
>>> nos.sort(key=len)
>>> nos
['two', 'One', 'Four', 'Five', 'Three']
>>>
Lists and functions
• Lists can be passed as arguments to a function
• Functions can then access and modify the
contents of the list.
• The changes made to the list within the
function body is permanent allowing to work
with large amounts of data efficiently
def listprocessing(num):
num.sort()
print(“list within the function=“, num)
return
n= [22,11,88,66,55]
print(“list before the function is called=“, num)
listprocessing()
print(“list after the function is called=“, num)
list before the function is called= [22,11,88,66,55]
list within the function= [11,22,55,66,88]
list after the function is called = [11,22,55,66,88]
Lists can be passed as arguments to functions
def sum(lst):
result=0
for item in lst:
result+=item
return result
def clear(lst):
for i in range(len(lst)):
lst[i]=0
def random_list(n):
import random
result = []
for i in range(n):
rand = random.randrange(100)
result+= [rand]
return result
>>> newlist=[1,2,3,4,5]
>>> sum(newlist)
15
>>> clear(newlist)
>>> newlist
[0, 0, 0, 0, 0]
>>> a= random_list(5)
>>> a
[84, 35, 84, 37, 84]
>>>
• Sometimes we need to prevent a function from
modifying a list.
• Here we need to pass the copy of the list and
not the original.
• Then changes happen only in the copy and the
original remains intact.
• The slice notation makes a copy of the list to
send to the function.
def listprocessing(num):
num.sort()
print("The list within the function = ", num)
return
>>>n=[33,22,55,11,66]
>>> print("The list before the function call = ", n)
The list before the function call = [33, 22, 55, 11, 66]
>>> listprocessing(n [:])
The list within the function = [11, 22, 33, 55, 66]
>>> print("The list after the function call = ", n)
The list after the function call = [33, 22, 55, 11, 66]
>>>
Python Tuples
• A tuple is a sequence of immutable Python objects
separated by commas.
• A tuple is different from the list in the following ways:
Tuples are defined with elements within
parenthesis whereas in a list the elements are defined
within square brackets.
List are mutable whereas tuples are immutable.
When the data is not changed overtime we choose
the tuple but when the data may be changed in the
future we choose the lists as the datatype.
Iterating over the elements of the tuple is faster
compared to iterating over a list.
Advantages of using a tuple over a list.
• Python programmers generally use tuple for
heterogeneous data types and lists for similar data
types, though both can store heterogeneous data.
• Since tuples are immutable iterating through a tuple is
faster than a list.
• Tuples that contain immutable elements can be used
as a key for a dictionary. With lists, this is not possible.
• If you have data that does not change, implementing it
as tuple will guarantee that it remains write protected.
Creating Tuples
• A tuple is created by placing all the items
inside parentheses, separated by commas.
• A tuple can have any number of items and
they can be of different types.
• The empty tuple
• Creating a tuple with one element
• Creating a tuple without parentheses
>>> my_tuple=()
>>> my_tuple
()
>>> my_tuple=(1,2,3)
>>> my_tuple
(1, 2, 3)
>>> my_tuple = (1,'Hello', 3.4)
>>> my_tuple
(1, 'Hello', 3.4)
>>> my_tuple=("Hello",(1,2,3),3.4)
>>> my_tuple
('Hello', (1, 2, 3), 3.4)
>>> my_tuple=1,2,3 #Without parentheses.
>>> my_tuple
(1, 2, 3)
>>> my_tuple=9 #treated as an integer variable
>>> my_tuple
9
>>> my_tuple=(10) #treated as an integer variable
>>> my_tuple
10
>>> my_tuple=(10,)
>>> my_tuple
(10,)
• A literal tuple containing many items can be
assigned to a single object.
• When this occurs it is as if the items are packed
into the object. This is called tuple packing.
• In packing we put the values into a regular tuple
variable by means of a regular assignment.
• If the packed object is subsequently assigned to a
new tuple, the individual items are unpacked into
the objects of the tuple.
• The total number of variables on the left hand
side should be equivalent to the total number of
value in the tuple. Else a ValueError is generated.
>>> t='foo','bar','baz','qux'
>>> t
('foo', 'bar', 'baz', 'qux')
>>> t[0]
'foo'
>>> t[-1]
'qux'
>>> (s1,s2,s3,s4)=t
>>> s1
'foo'
>>> s2
'bar'
>>> s3
'baz'
>>> s4
'qux‘
>>>
• Packing and unpacking can be combined into a
single compound statement.
(s1,s2,s3,s4) = ('foo', 'bar', 'baz', 'qux')
Accessing Tuple elements
Indexing
• The index operator can be used to access a
tuple element. The index starts at 0.
• The index must be an integer else a TypeError
is generated.
• Trying to access an element outside the tuple
generates a IndexError.
• Nested tuple elements are accessed using
nested indexing.
• Negative indexing is also possible.
>>> my_tuple=(1,2,3)
>>> my_tuple[0]
1
>>> my_tuple[-1]
3
>>> my_tuple[-2]
2
>>> my_tuple=("Hello", (1,2,3), [4,5,6],3.4)
>>> my_tuple
('Hello', (1, 2, 3), [4, 5, 6], 3.4)
>>> my_tuple[1]
(1, 2, 3)
>>> my_tuple[1][1]
2
>>> my_tuple[2]
[4, 5, 6]
>>> my_tuple[2][0]
4
>>>
Slicing
• A range of items can be accessed using the
slicing operator.
• The range can be specified using the start and
end indexes.
• The return value will a new tuple with the
specified items in the range.
>>> my_tuple=(1,2,3,4,5,6,7)
>>> my_tuple[2:6]
(3, 4, 5, 6)
>>> my_tuple[7:]
()
>>> my_tuple[2:]
(3, 4, 5, 6, 7)
>>> my_tuple[2:4]
(3, 4)
>>> my_tuple[:-6]
(1,)
>>> my_tuple[:-4]
(1, 2, 3)
>>> my_tuple[0]
1
>>> my_tuple[0:1]
(1,)
>>> my_tuple[:]
(1, 2, 3, 4, 5, 6, 7)
>>>
Tuple Operations
len((1,2,3)) 3 Finds the length
(1,2,3) + (4,5,6) (1,2,3,4,5,6) Concatenation
(‘Hi!,) *4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1,2,3) True Membership
not in
for x in (1,2,3): 1 Iteration
print (x) 2
3
Both the ‘+’ and the ‘*’ operators create new tuples.
Tuples are immutable . That is the elements of
the tuple cannot be changed once it is
assigned.
But if the element itself is a mutable list, the
nested items can be changed.
A tuple can be reassigned with different values.
Since the tuples are immutable, the individual
elements cannot be deleted. But the entire
tuple can be deleted using the keyword del.
del myTuple
where myTuple is a tuple variable.
Tuple Methods
• Python has two built-in methods:
count()
index()
count(): Returns the number of times a specified value occurs
in a tuple.
syntax:
tuple.count(value)
where value is the item to search for
>>> myTuple=(1,3,5,8,5,2,4,9,5)
>>> myTuple.count(5)
3
index()
The index() finds the first occurrence of the specified value. An
exception is raised if the value is not found.
syntax:
tuple.index(value)
where value is the item to search for
>>> myTuple=(1,3,5,8,5,2,4,9,5)
>>> myTuple.index(5)
2
>>> myTuple.index(10)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
myTuple.index(10)
ValueError: tuple.index(x): x not in tuple
>>>
Python Dictionaries
• A dictionary is a collection of changeable
indexed and unordered key, value pairs.
• The keys must be unique and they can be
stored in unordered sequence.
• Each key-value pair is separated from each
other by colons key:value and the key-value is
separated from other key-value pairs by
commas. The key-values are given in curly
brackets.
• The keys must be unique and must be of
immutable data type such as strings, integers
and tuples
• The key-values can be repeated and can be
any data type.
Creating Dictionaries
• A dictionary is created by placing sequence of elements within
curly braces and is separated by commas.
• The dictionary holds a pair of values, one being the key and the
other corresponding pair element being its value.
• Values can be duplicated but keys cannot be repeated and must be
immutable.
• Keys are case sensitive. Thus there can be keys with same name
but different cases.
>>> stud_info={'name':'John','age':20,'class': 'B.Sc'}
>>> stud_info
{'name': 'John', 'age': 20, 'class': 'B.Sc'}
>>> fruits={1:'Apple',2:'Orange',3:'Cherry', 4:'Banana'}
>>> fruits
{1: 'Apple', 2: 'Orange', 3: 'Cherry', 4: 'Banana'}
>>>
• The keys must be unique and must be of
immutable data type such as strings, integers
and tuples
• The key-values can be repeated and can be
any data type.
• Dictionaries can also be created by the built-in function dict().
• An empty dictionary can be created using the dict() with curly
braces
>>> var=dict({})
>>> var
{}
>>> newdict=dict({1:'Apple',2:'Orange',3:'Cherry', 4:'Banana'})
>>> newdict
{1: 'Apple', 2: 'Orange', 3: 'Cherry', 4: 'Banana'}
>>> newdict1=dict([(1,'Apple'),(2,'Banana')])
>>> newdict1
{1: 'Apple', 2: 'Banana'}
>>>
Accessing elements from Dictionary
• Dictionaries uses the keys to access the elements.
• Key can be used either inside the square brackets or with the get() method. If the key
is not found the get() method returns None instead of KeyError.
>>> stud_info={'name':'John','age':20,'class': 'B.Sc‘}
>>>stud_info
{'name': 'John', 'age': 20, 'class': 'B.Sc'}
>>> stud_info['name']
'John'
>>> stud_info['age']
20
>>> newdict=dict({1:'Apple',2:'Orange',3:'Cherry', 4:'Banana'})
>>> newdict[1]
'Apple'
>>>>>> print('stud_info.get(\'age\')=', stud_info.get('age'))
stud_info.get('age')= 20
>>>
Change/Add elements into a Dictionary
• Dictionaries are mutable.
• New items can be added using the assignment operator.
• If the key is already present the value gets updated, else a new
key:value pair is added.
>>> stud_info={'name':'John','age':20,'class': 'B.Sc'}
>>> stud_info
{'name': 'John', 'age': 20, 'class': 'B.Sc'}
>>> stud_info['name']='Ramkumar'
>>> stud_info
{'name': 'Ramkumar', 'age': 20, 'class': 'B.Sc'}
>>> stud_info.update({'admin_no':112200})
>>> stud_info
{'name': 'Ramkumar', 'age': 20, 'class': 'B.Sc', 'admin_no': 112200}
Delete elements in a Dictionary
pop()- It removes an item with the provided key
and returns the value.
popitem()- Can be used to remove and return an
arbitrary item(key,value) from the dictionary.
clear() – all the items can be removed at once
del keyword – Removes the individual items or
the entire dictionary itself.
>> stud_info={'name':'Ramkumar','age':20,'class':
'B.Sc','admin_no':112200}
>>> stud_info
{'name': 'Ramkumar', 'age': 20, 'class': 'B.Sc', 'admin_no': 112200}
>>> stud_info.pop('name')
'Ramkumar'
>>> stud_info
{'age': 20, 'class': 'B.Sc', 'admin_no': 112200}
>>> stud_info.popitem()
('admin_no', 112200)
>>> stud_info
{'age': 20, 'class': 'B.Sc'}
>>> stud_info.popitem()
('class', 'B.Sc')
>>>stud_info.update([('name','John'),('age',33)])
>>> stud_info
{'age': 33, 'admin_no': 112200, 'name': 'John'}
>> del stud_info['name']
>>> stud_info
{'age': 33, 'admin_no': 112200}
>>> stud_info.clear()
>>> stud_info
{}
>>> del stud_info
>>> stud_info
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
stud_info
NameError: name 'stud_info' is not defined
>>>
Membership operation
• Using the operators in and not in
• Checks if a key is in the dictionary or not
• The membership test is done only for the keys and not for the values.
>> stud_info={'name':'John','age':20,'class': 'B.Sc'}
>>> stud_info
{'name': 'John', 'age': 20, 'class': 'B.Sc'}
>>> print('admin number is not in stud_info', 'admin_no' not in stud_info)
admin number is not in stud_info True
>>> print('name is in stud_info :', 'name' in stud_info)
name is in stud_info : True
>>> print('John is in stud_info :', 'John' in stud_info)
John is in stud_info : False
>>>
• for loop can be used to iterate through each key in
a dictionary.
>>> stud_info
{'name': 'John', 'age': 20, 'class': 'B.Sc'}
>>> for i in stud_info:
print(stud_info[i],end=' ')
John 20 B.Sc
>>>
Built –in functions with dictionary
all() Return True if all the keys of the dictionary are true(or if
the dictionary is empty)
any() Return True if any key of the dictionary is true. If the
dictionary is empty ,return False.
len() Return the length or the number of items in the dictionary.
cmp() Compares items of two dictionaries.
sorted() Return a new sorted list of keys in the dictionary.
>>> stud_info
{'name': 'John', 'age': 20, 'class': 'B.Sc'}
>>> print('The number of items in the dictionary is=',len(stud_info) )
The number of items in the dictionary is= 3
>>> print('The sorted dictionary is=',sorted(stud_info))
The sorted dictionary is= ['age', 'class', 'name']
>>>
Dictionary methods
• clear()
Removes all the elements from the dictionary.
dictionary.clear()
• copy()
Returns a copy of the dictionary.
dictionary.copy()
>>> copy_dict=stud_info.copy()
>>> copy_dict
{'name': 'John', 'age': 20, 'class': 'B.Sc'}
>>>
• fromkeys()
Returns a dictionary with the specified keys and values.
dictionary.fromkeys(keys,value)
keys- Required. An iterable specifying the keys of the new dictionary.
value – Optional. The value for all keys. Default value is None
>>> seq=('name','age','sex')
>>> seq
('name', 'age', 'sex')
>>>dist= dict.fromkeys(seq)
>>> dist
{'name': None, 'age': None, 'sex': None}
>>> dist = dict.fromkeys(seq,10)
>>> dist
{'name': 10, 'age': 10, 'sex': 10}
>>>
• get()
Returns the value of the specified key.
dictionary.get(keyname,value)
keyname- Required. The keyname of the item you want to return the value from.
value – Optional. The value to return if the specified key does not exist . Default value is
None
>>> studinfo={'name':'John', 'class':'B.Sc Physics','admno':1234}
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'admno': 1234}
>>> studinfo.get('name')
'John‘
>>> studinfo.get('name','None')
'John‘
>>> studinfo.get('address','None')
'None'
• items()
Returns a list containing a tuple for each key value pair.
dictionary.items()
>>> studinfo={'name':'John', 'class':'B.Sc Physics','admno':1234}
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'admno': 1234}
>>> studinfo.items()
dict_items([('name', 'John'), ('class', 'B.Sc Physics'), ('admno',
1234)])
>>>
• keys()
Returns a list containing the dictionary’s keys.
dictionary.keys()
>>> studinfo={'name':'John', 'class':'B.Sc
Physics','admnno':1234}
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'admno': 1234}
>>> studinfo.keys()
dict_keys(['name', 'class', 'admno'])
>>>
• values()
Returns a list of all the values in the dictionary
dictionary.values()
>>> studinfo={'name':'John', 'class':'B.Sc
Physics','admno':1234}
>>> studinfo
{ 'John', 'class': 'B.Sc Physics', 'admno': 1234}
>>> studinfo.values()
dict_values(['John', 'B.Sc Physics', 1234])
• pop()
Removes the element with the specified key. The value of the removed item is the return
value of the pop() method.
dictionary.pop(keyname,defaultvalue)
keyname- Required. The keyname of the item you want to remove.
defaultvalue – Optional. The value to return if the specified key does not exist . If this
parameter is not specified and there no item is found with the specified key, an error
is raised.
>>> studinfo={'name':'John', 'class':'B.Sc Physics','admno':1234}
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'admno': 1234}
>>> studinfo.pop('name')
'John'
>>> studinfo
{'class': 'B.Sc Physics', 'admno': 1234}
>>>
• popitem()
Removes the inserted key-value pair. The removed item is
the return value of the popitem() method.
dictionary.popitem()
>>> studinfo={'name':'John', 'class':'B.Sc
Physics','admno':1234}
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'admno': 1234}
>>> studinfo.popitem()
('admno', 1234)
>>>
• setdefault()
Returns the value of the specified key. If the key does not exist, insert the key,
with the specified value.
dictionary.setdefault(keyname, value )
keyname- Required. The keyname of the item you want to return the value
from.
value – Optional. If the key exists, this parameter has no effect. If the key does
not exist , this value becomes the key’s value. Default value None
>>> studinfo={'name':'John', 'class':'B.Sc Physics','admno':1234}
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'admno': 1234}
>>> studinfo.setdefault('category', 'UG')
'UG'
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'category': 'UG'}
>>>
• update()
Updates the dictionary with the specified key-value pairs.The
specified items can be a dictionary, or an iterable object.
dictionary.update(iterable)
Iterable - A dictionary or an iterable object with key value pairs, that
will be inserted to the dictionary
>>> studinfo={'name':'John', 'class':'B.Sc Physics','admno':1234}
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'admno': 1234}
>>> studinfo.update({'admno': 5678})
>>> studinfo
{'name': 'John', 'class': 'B.Sc Physics', 'category': 'UG', 'admno': 5678}
>>>
Python Sets
• Set is an unordered and unindexed collections of
items.
• Every element is unique with no duplicates and
must be immutable
• But the set itself is mutable
• You can add or remove items from it
• Set elements can of any data type and are not
data type specific
• Any immutable data type can be an element of a
set like a number, string and a tuple.
Creating Sets
• Placing the items inside { }
• A set can have any number of items and can of any data type
• Mutable items cannot be elements of a set like a list, set or dictionary as its elements
• A tuple can be the element of a set
>>> my_set={1,2,3}
>>> my_set
{1, 2, 3}
>>> my_set={"BCA","B.Sc","BA"}
>>> my_set
{'BA', 'B.Sc', 'BCA'}
>>> my_set={1.0,"BCA",(1,2,3)}
>>> my_set
{1.0, (1, 2, 3), 'BCA'}
#a set cannot have duplicate values
>>> my_set={1,2,3,3,2,4}
>>> my_set
{1, 2, 3, 4}
• A set can also be created using the set() function
x = set(<iter>)
iter is a list of objects generated that are to be included in the list.
>>> my_set= set((1,2,3,4))
>>> my_set
{1, 2, 3, 4}
>>> my_set=set(["BCA","B.Sc","BA"])
>>> my_set
{'BA', 'B.Sc', 'BCA'}
• set(string ) generates a set of characters in the string
>>> my_Set=set("Hello! How are you")
>>> my_Set
{'a', 'w', 'l', 'o', '!', 'u', 'e', 'y', ' ', 'r', 'H'} #duplicate val avoided and is unordered
>>>
• A set can be empty
• But an empty {} is taken as an empty dictionary
• So the set() is used for creating empty sets
>>> a={}
>>> print('type(a) =', type(a))
type(a) = <class 'dict'>
>>> a=set()
>>> print('type(a) =', type(a))
type(a) = <class 'set'>
>>>
Accessing and Changing a set
• Set elements are immutable but as a whole they are mutable
• They are unordered and hence accessing or changing an element of the set cannot be done using
slicing or indexing.
• Single elements can be added- add()
• Multiple elements can be added- update(). It takes tuples, lists, strings or sets as args.
>>> my_set= {1,3}
>>> my_set
{1, 3}
>>> my_set.add(2)
>>> my_set
{1, 2, 3}
>>> my_set.update([2,3,4])
>>> my_set
{1, 2, 3, 4}
>>> my_set[0]
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
my_set[0]
TypeError: 'set' object is not subscriptable
Removing elements from a set
• Using discard() and remove()
• If the element does appear in the list the remove() raises an error whereas discard() does not
>>> my_set
{1, 2, 3, 4}
>>> my_set.discard(4) #set.discard(item)
>>> my_set
{1, 2, 3}
>>> my_set.remove(3) #set.remove(item)
>>> my_set
{1, 2}
>>> my_set.discard(4)
>>> my_set
{1, 2}
>>> my_set.remove(4)
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
my_set.remove(4)
KeyError: 4
>>>
• pop()- removes and returns the item but the popped item is arbitrary as
sets are unordered
• clear()- removes all the items in the set
>>> my_set = {1,2,3,4,5}
>>> my_set
{1, 2, 3, 4, 5}
>>> my_set.pop()
1
>>> my_set.pop()
2
>>> my_set
{3, 4, 5}
>>> my_set.clear()
>>> my_set
set()
>>>
Set Operations
Set Union
• All elements of both the sets A and B
• Performed using | operator or union()
>>> A={1,2,3,4}
>>> A
{1, 2, 3, 4}
>>> B ={3,4,5,6}
>>> B
{3, 4, 5, 6}
>>> A|B
{1, 2, 3, 4, 5, 6}
>>> A.union(B) #set.union(set)
{1, 2, 3, 4, 5, 6}
>>> B|A
{1, 2, 3, 4, 5, 6}
Set Intersection
• elements common to both the sets A and B
• Performed using & operator or intersection()
>>> A={1,2,3,4}
>>> A
{1, 2, 3, 4}
>>> B ={3,4,5,6}
>>> B
{3, 4, 5, 6}
>>> A & B
{3, 4}
>>> A . intersection(B)
{3, 4}
>>> B & A
{3, 4}
>>>
Set Difference (A-B)
• elements that are only in A but not in B
• B - A is elements that are only in B but not in A
• Performed using - operator or difference()
>>> A
{1, 2, 3, 4}
>>> B
{3, 4, 5, 6}
>>> A - B
{1, 2}
>>> B - A
{5, 6}
>>> A . difference(B) #A-B
{1, 2}
>>> B . difference(A) #B-A
{5, 6}
>>>
Set Symmetric Difference
• elements in both A and B except those that are common in both
• Performed using ^ operator or symmetric_difference()
>>> A
{1, 2, 3, 4}
>>> B
{3, 4, 5, 6}
>>> A^B
{1, 2, 5, 6}
>>> B^A
{1, 2, 5, 6}
>>> A.symmetric_difference(B)
{1, 2, 5, 6}
>>>
Set Membership test
• Using in and not in to test whether an item exists or not
>>> A
{1, 2, 3, 4}
>>> 1 in A
True
>>> 9 in A
False
>>> 1 not in A
False
>>> 9 not in A
True
>>>
Iterating through a set
• Using for loop
>>> my_set=set("hello! how are you")
>>> my_set
{'w', 'h', 'l', 'o', '!', 'u', 'e', 'y', ' ', 'r', 'a'}
>>> for letter in my_set:
print(letter, end=' ')
whlo!uey ra
>>>
Built in functions with set
• all() – returns true if the set is empty or if all the
elements of the sets are true
• any() – returns true if any element of the set is
true. If the set is empty returns false.
• len() – no of items
• max()- returns the largest element
• min()
• sorted()- returns a new sorted list from the
elements in the set. Does not sort the original set
• sum() – sum of all elements of the set
Set Methods
add()
clear()
difference()
copy()- copies the set
>>> A
{1, 2, 3, 4}
>>> C= A.copy() # set_var=set.copy()
>>> C
{1, 2, 3, 4}
>>>
difference_update()
removes the items that exist in both sets. The items are removed in the original set.
Whereas when difference() is used a new set is returned without the unwanted
elements.
Syntax:
set.difference_update(set)
>>> A
{1, 2, 3, 4}
>>> B
{3, 4, 5, 6}
>>> A.difference_update(B)
>>> A
{1, 2}
>>> B
{3, 4, 5, 6}
>>>
discard()
intersection()
intersection_update() – removes the items that are not present in both the sets or the multiple sets.
The change is reflected in the original set. Where when the intersection() a new set is returned.
Syntax:
set.intersection_update(set1,set2,…..)
>>> A={1,2,3,4}
>>> A
{1, 2, 3, 4}
>>> B
{3, 4, 5, 6}
>>> A.intersection_update(B)
>>> A
{3, 4}
>>> B
{3, 4, 5, 6}
>>> C={3,8,9,7}
>>> A.intersection_update(B,C)
>>> A
{3}
>>> B
{3, 4, 5, 6}
>>> C
{8, 9, 3, 7}
>>>
isdisjoint() – returns True if none of the items are present in both sets else False.
Syntax:
set.isdisjoint(set)
>>> A
{3}
>>> B
{3, 4, 5, 6}
>>>
>>> A.isdisjoint(B)
False
>>> A={ 1,2,3}
>>> A
{1, 2, 3}
>>> B={5,6,7}
>>> B
{5, 6, 7}
>>> A.isdisjoint(B)
True
>>>
issubset() – returns True if all items in the set exists in the specified set else
False.
Syntax:
set.issubset(set)
>>> x={"a","b","c"}
>>> x
{'b', 'c', 'a'}
>>> y={"f","e","d","c","b","a"}
>>> y
{'d', 'c', 'f', 'e', 'b', 'a'}
>>> x.issubset(y)
True
>>> y.issubset(x)
False
>>>