PYTHON BASICS class 11 cs
PYTHON BASICS class 11 cs
These are
1. Python character set
2. Keywords
3. Comments
4. Constants
5. Operators
6. Variables
7. Data Types
Let us discuss each one of these in detail. Operators, variables and data types are covered in detail
in the website.
Character Set :
A character set of a language is the range of permissible characters that can be used in a program
written in that language. The Python language includes the following character set :
All the ASCII letters, ie. A-Z,a-z, 0-9, special characters like +,-,#,%, *,/,//,% and many more.
Keywords
A keyword is a word that has some predefined meaning in the language. These are also known as
reserved words. Some characteristics of keywords:
Keywords(Reserved words) are written in lowercase except a few in sentence case(False,
None and True).
We cannot use a keyword as variable name, function name or any other identifier.
Keywords can be altered in different versions of Python. To view the complete list of keywords, we
can use the following code:
Comments
In programming languages, comments are used to describe or explain the purpose of the code. We
can compare it to labeling a diagram in science. Comments are not executed and are completely
ignored by compilers and interpreters.
In Python any text written to the right of a # is a comment.
For example:
Escape Sequences: These are special constants which have a functionality attached to them. We
can use them mostly with the print statement to give variation in output. Listed below are some
escape sequences with their explanation.
Variables
In Python, variables are treated as objects. This means that a variable in Python refers to a value
stored in the computer memory.
Every variable has a:name, value and a data type associated with it. So the statement :
>>>x = 8
declares a variable with the name x , having value 8 and type integer .
Let us consider another example :
>>>name="Computer Science"
In the above statement a variable name of the type string is declared with the value "Computer
Science".
So the general statement of declaring a variable with a value will be:
The variable will be assigned the value given on the right hand side.
Example:
>>> a=90
>>> a
90
>>> 56=b
SyntaxError: can't assign to literal
Identifiers
The name of a variable is also called an identifier. An identifier is a name given to any object in
Python. When we name an object some rules have to be followed. These are :
The first character of the identifier must be a letter of the alphabet (uppercase or lowercase
character ) or an underscore (_).
The rest of the identifier name can consist of letters (uppercase or lowercase ), underscores
(_) or digits (0-9).
Python is a case sensitive language. Thus identifier names are also case-sensitive. For
example, RollNo and rollno are not the same.
Examples of valid identifier names are _age, name, a9999, Student_Id.
A keyword cannot be used as an identifier
Examples of invalid identifier names are .
Data Types
A data type defines a set of values and the operations that can be performed on an object/variable of
that type...
Need for Data Types :
When programming, we store the data in our computer's memory. As we all know that a
computer is just a machine. It cannot by itself distinguish between various types of Data. This means
that it cannot distinguish between the number 20 and the letter ‘A’ or the word “good” . For the
computer all of this is just a piece of data.
It is the programmer who must tell the computer that 20 is a number, ‘A’ is a character and
‘good’ is a word. How do we do it?
By using data types we can classify the different data for the computer so that it can be
stored and processed in a certain manner.
This is because all the data does not occupy the same amount of memory and they are not
going to be interpreted the same way.
1. Numbers : These type of data include all numbers. All operations that can be performed on
numeric data apply to these types. There are three sub types; integer, float and complex.
a. Integer : Whole numbers are treated as integers in Python. To declare a variable of type integer
we can simply assign a whole number to a variable.
>>>x=45
Here x is a variable pointing to the constant 45.
In Python, an integer can be of any length. This means you can assign any whole number to an
integer. It depends on the available memory. Typical examples to use integer variables would be to
store age, roll number etc.
b. Floating point : Fractional numbers are treated as float type in Python. So for example 22.5,
45.69034 etc. are data of type float. Floating point variables can be used to store values such as
salary, rate of interest etc.
>>>y=24.9008
Here the variable y is of type float. The float variables have a decimal point.
c. Complex : Python provides us with a way to represent complex numbers. Complex numbers
have a real part and an imaginary part. For example A+Bj is a complex number where A is
the real part and B is imaginary. Both A and B are floating point number and j represents the square
root of an imaginary number.
To extract the real and imaginary parts of a complex number z, we can use the
statements, z.real, z.imag.
Example
>>>x=4+7j
>>>print(x.real, x.imag)
4.0 7.0
2. Strings. A string is a sequence of characters that can be taken from the Python character set.In
Python strings are known as str. A string can include alphabets, numbers and special symbols
enclosed in single ,double or triple quotes.
Examples of string declarations
>>>a='Good Morning'
>>>print(a)
Good Morning
>>>str1="Python#3.0 is a fun language"
>>print(str1)
Python#3.0 is a fun language
3. None : The none type in Python defines null or no value at all. It is different from the value 0.
None is also a keyword in Python.To define a variable of none type, we write the following code :
>>> x= None
>>> print(x)
None
>>>y=None
>>>y
>>>
No value is printed when we type y at the prompt. Note the capital N in the keyword None.
4. Boolean : A variable of type Boolean can have any of the two values; true or false. We shall
cover more on Boolean variables in the topic, control structures.
>>> x=34
>>> type(x)
<class 'int'>
Similarly
>>>name="Casablanca"
>>>type(name)
<class 'str'>
>>>x=9
>>>print(x)
9
>>>x=34
>>>print(x)
34
The constant values are stored in the memory having a fixed address. A variable when assigned a
constant value, points to that particular value.
Consider the given code and the corresponding memory map.
>>> x=24
>>> y=35
>>> x
24
>>> y
35
We can see that the data type of x is int at first and then it changes to float. This is unlike most of
the programming languages where the data type of a variable remains static(cannot be changed),
once declared.
In Python we can assign a variable with data of any type during the course of a program.The data
type of a variable varies according to the value assigned to it. For example
>>>x=45
>>>x
45
>>>type(x)
<class 'int'>
>>>x="Good Morning"
>>>x
'Good Morning'
>>>type(x)
<class 'str'>
In the above code the data type of the variable x automatically changes when we assign a string
literal to it. We can assign a value of any data type to a variable in the course of a code. This is
known as Dynamic Binding.
1. We can assign the same value to multiple variables in the same statement.
variable1=variable2=variable3=.......=value
The statement above assigns the same value to variable1, variable2 etc.
Example:
tsum=count=0
2. We can also assign multiple values to multiple variables using a single statement:
var1,var2,var3,.....,valn=val1,val2,val3,.......,valn
Example:
>>>x=y=z=24
>>>x,y,z
>>>(24,24,24)
>>> a,b,c="Hello","How","are"
>>> a,b,c
('Hello', 'How', 'are')
>>> a,b,c="hello",2,9.8
>>> a,b,c
('hello', 2, 9.8)
Type Conversions
Python provides some simple built in functions to convert variables from one type to the other:
1. int()
Converts an object to integer. The object can be a float variable or a string made up of numbers.
Example:
>>> x=9.0 # Here x is a float variable
>>> print(int(x))
9
2. float()
Converts an object to float. The object can be an integer variable or a string made up of decimal numbers.
Example:
>>> x=45 # Here x is an int variable
>>> print(float(x))
45.0
3. str()
Converts an object to a string type where the object n]can be an integer or float.
Example:
'38'
4. chr()
This function gives the character representation if a number according to the ASCII code. (code
which represents each character on the keyboard)
>>> z=90
>>>chr(z)
'Z'
This means Z (capital) is represented by the ASCII code 90.
Type casting
We can modify the data type of the result of an expression involving same or multiple data types.
This is known as type casting.
Example 1:
>>> print(24.5+67.8)
92.3 #without typecasting
>>> print(int(24.5+67.8))
92 #casting to int()
Example 2:
>>> print(90+20)
110
>>> print(float(90+20)) #casting to float()
110.0
However, it is important to note that type casting just casts the value of an expression or variable, it
does not change the original data type of a variable.
Example 3:
>>> x='90'
>>> print(int(x))
90
>>> x+80
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
x+80
TypeError: must be str, not int
In the above example, the variable x is of string type. We can cast it to int and display the value as int. But
when we try to add it to an integer a type mismatch error is shown.
But we can add the cast value of x as shown in the example below
Example 4:
>>> print(int(x)+70) #casting x to int and adding in an expression
160
>>> b=45
>>> print(str(b))
45
>>> b+90
135
The input() function
The input function is prompts the user to enter some value. When the user enters the text and presses enter, this
text is returned and usually stored in a variable.
Example:
In the above code the variable name is used to store the value returned by the input() function. When we run
the above program in script mode the following output is generated:
The name is keyed in and the screen now looks like this:
The first line prompts the user to enter name. When the name 'Falguni' is entered, it is stored in the variable
name which accepts it as a string.
The input() function always returns a string. In order to use input() with numbers we need to typecast the
return value using the int() ,float() or eval() functions.
Example
marks=int(input("Enter marks : "))
print(marks)
In the above code the int() function converts the input string to an integer which is then stored in the variable
marks.
Output:
Enter marks : 56
56
Example:
Interest=float(Input("Enter rate of interest ")
print("You have to pay interest %: ", Interest)
Output:
Enter rate of interest 6
You have to pay interest %: 6
Note: When entering the values using input() method, you need to ensure that the value entered is of the
target type.
For example if we enter a float value when using the int() function with input(), an error is generated.:
Similarly,
>>> comm=float(input("Enter Commission"))
Enter Commission 89.9%
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
comm=float(input("Enter Commission"))
ValueError: could not convert string to float: ' 89.9%'
Sample Program: Input the Principal, Rate and time in years and calculate the Simple Interest.
To print more than one object (variable, constant or string) we can simply use commas in between.
Examples:
>>>print("Hello", "Welcome")
Hello Welcome #Automatically inserts space pace in between the
strings as the
default sep=' '
>>>print("The sum of ", 45, " and ", 65, "is :", 45+65)
The sum of 45 and 65 is :110 #printing different types of objects
The sep parameter can be used to separate text or data using any character like a comma, semicolon etc.
Examples:
>>> print("Name","Place","Animal","Thing", sep=',')
Name,Place,Animal,Thing # A comma is used as a separator
The default value of the end argument of the print() command is a newline('\n'). So a newline is appended to
the output if not specified otherwise. But we can specify any character to be printed at the end.
Examples:
>>>print("It will be", 7800/2,sep=":", end="Rs") # The letters Rs in the parameter end is printed
after the output
It will be:3900.0Rs
In the script mode when we write consecutive print statements the output is displayed on separate lines. But
if we wish to print the output of both statements on same line we can assign a ' ' to the parameter end.
print(67+78,end=' ')
print(45+90)
Output:
145 135
Sample Program: Write a program to input the radius of a circle and calculate the area and circumference.
Operators and Expressions
Table of Contents
Arithmetic Operators
Arithmetic with Strings
Relational Operators
Logical Operators
Operator Precedence
Assignment Operators
Expressions
Sample Program
Math Module
Operators
Operators are special symbols that are used for computations in Python. The
operators .require operands which can be variables and/or constants to work on. An
example of an operator would be +. An expression is a combination of an operator and its
operands; for example. 4+5. The operators in Python can be categorized as : Arithmetic,
Relational, Logical, assignment and Identity operators.
Arithmetic Operators
These operators work on numeric values . The operators can be further
categorized according to the number of operands they require. Unary operators work on a
single operand whereas binary works on two operands. Let us examine each one in detail.
Using +
>>> "Hello" +"Python"
'HelloPython'
>>> x="Good"
>>> y="Morning"
>>> x+y
'GoodMorning'
Using *
>>> "Ball" * 2
'BallBall'
>>> y="Frog"
>>> y*4
'FrogFrogFrogFrog'
Relational operators
These are also known as relational operators. When applied they return a value True or
False.
>>> 60>90
False
>>> 99<200
True
>>> a=45
>>> b=34
>>> a>b
True
>>> a<b
False
>>> a==b
False
>>> a!=b
True
>>> x=90
>>> y=90
>>> x>=y
True
>>> x=99
>>> x>=y
True
We can use relational operators with strings also. When we use them with strings , the
strings are compared from left to right, using the ASCII values of the characters. The strings
are always compared in a lexicographical manner i.e. according to their appearance in the
dictionary.
For example:
>>>"Hello"<"hello"
True
This is because the ASCII code of 'H' is 65 and that of 'h' is 104. Therefore "Hello" is smaller
than "hello"
>>> "yearly"<"monthly"
False
Logical Operators
These operators are used to join expressions containing arithmetic and /or relational
operators to form complex expressions. There are three logical operators and, or and not.
Consider the following table. Here x and y are two expressions.
Using not in code
>>> x=99
>>> y=89
>>> z=90
>>> not x>80
False
>>> not y<80
True
Using and
>>> x=99
>>> y=89
>>> z=90
>>> x>y and z>60
True
>>> x>z and y!=z
True
>>> z<x and y>=40
True
>>> z<x and y>x
False
Using or
>>> x=99
>>> y=89
>>> z=90
>>> x<y or x!=80
True
>>> x==99 or z<80
True
>>> y>z or x>y
True
>>> x<y or z<y
False
Operator precedence
When we have expressions with more than one operator, it becomes ambiguous as to
which operation to perform first, which to perform second and so on. Therefore every
language assigns a precedence to all the operators that are supported.
So therefore in an expression, an operators of highest precedence are applied first.
Operators of the next highest precedence are performed and so on till the expression is fully
evaluated. Any operators of equal precedence are performed in left-to-right order.
Python assigns the following precedence to various operators:
In the above table the operators are arranged in descending order of precedence with
exponentiation having highest precedence and logical or having lowest precedence. The
operators having same precedence are arranged in a single row and they evaluate from left
to right.
Example of operator precedence:
>>> 4+5*9-2
47
>>> 3**4*2
162
In the first statement, first 5 is multiplied by 9, the product, 45 is added to 4 to obtain the
sum, 49. 2 is then subtracted from 49 to give final result 47. Similarly in the second
statement 3 is first raised to power 4 and the result is multiplied by 2.
>>> (4+5)*9-2
79
>>> 3**(4+2)
729
The operation in the brackets are always performed first. Therefore in the first statement,
the parenthesized expression, (4+5) is evaluated first (4+5=9), which is multiplied by 9
(9*9=81), and finally 2 is subtracted from the result(81-2=79.
We can use any number of brackets in an expression.
>>>x=4
>>>x=x+2
>>>x
6
The value of x is 4. When we add 2 to it, the value becomes 6. Note that the variable x is
incremented, therefore it is present on both sides of the = (assignment) operator. Python
provides shorthand assignment operators which can be used for this purpose. These are:
Hence the above code can be written as :
>>>x=4
>>>x+=2
>>>x
6
Expressions
An expression may consist of a combination of:
variables
constants
operators
An expression needs to be evaluated thus it is usually assigned to a variable or appears in
a print statement.
Examples of expressions are:
The expression may be arithmetic, logical or conditional depending on the operators used. It
may be a combination of all.
Using expressions:
>>> a=24+30-9*2
>>> a
36
>>> b=a+20
>>> b
56
>>> a=b>9
>>> a
True
>>> 20+90/8-2
29.25
>>>
Write a program to input two numbers and display the sum, product, quotient and product
a=int(input("Enter a number"))
There are some operations like finding the square root or raising a number to a power. For
example to express the following equation in Python, we shall require special functions
other than the operators.
x=
The math module in Python contains a collection of mathematical functions which enable
such complex mathematical calculations or equations to be expressed. In this section we
shall cover only two such functions, math.pow() and math. sqrt(). We shall cover the module
in detail in a later unit.
In order to be able to use the functions in the math module we need to first import it using
the following statement:
import math
1. math.pow(x,y)
This function returns the value of x raised to the power y.
Example:
>>> import math
>>> print(pow(2,4))
16
2. math.sqrt(x)
This function returns the square root of the number x. x must be a positive number.
Example:
Example:
>>> import math
>>> print(math.sqrt(-16))
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print(math.sqrt(-16))
ValueError: math domain error
So now to express the given equation in Python :
x=
Selection control statements are used to make one times decisions in programs. They help choose a
certain course of action depending on a given condition.
The if statement
This is the most basic type of control statement that can be used to implement decision making. The
if statement is used to execute an instruction or a set of instructions only if a condition/Test
expression is fulfilled or satisfied. The syntax is :
if test expression:
statement
The statement is executed only if the test expression evaluates to true.Note the colon after
expression. It is part of the syntax and is mandatory. Also note the indentation in the second line.
This indicates the body of if . If more than one statement needs to be executed , all of them must
start with this indentation. The first unindented line of code marks the end of if.
If flowchart:
Example:
Idle mode
>>> x=22
>>> if x>=18 : #True
print("Ready to Vote")
Ready to Vote
Note that in idle mode after pressing enter after the print statement , nothing happens. You need to
press enter again in order to run the code. This is because if is a multi line statement. But in Script
mode we do not need to do this
Script Mode
x=22
if x>=18:
print ("Ready to Vote")
Ready to Vote
x=15
if x>=18:
print("Ready to Vote")
The above code will not give any output as the condition evaluates to false and there is no statement
following the if block.
More examples
a=4
if a>0:
print ("Positive)
print ("out of if")
Output:
Positive
Out of if
In the above example a>0 is the test expression. It evaluates to true, so the statement
print(:positive") is executed. The next line is print("Out of if") is also executed as the body of if ends
here.
Now consider this code:
a=-2
if a>0:
print ("Positive)
print ("out of if")
Output:
Out of if
In the second code snippet, the test expression evaluates to false, therefore the statement
print("Positive") is not executed. However the next statement is executed as it is not part of if.
At times it is required to execute more than one statement if the test expression evaluates to true.
We call this a block of statements. To ensure this all the statements in the block should be indented
with the same number of spaces. It is usually 4 spaces.
x=45
if x>20 :
print("This is a program")
print("Use Editor")
Output:
This is a program
Use Editor
The if......else statement
The if…else statement is a variation of the simple if.. in that it provides an alternative if condition
evaluates to false. If the test expression evaluates to false the statement(s) following the else are
executed.
Definition
The if.. else statement executes the statement(s) given in the if block if the test expression/condition
evaluates to true otherwise it executes the statement(s) in the else block.
SYNTAX
if test Expression:
Statement 1; #if block
else:
Statement 2; #else block
If the conditional expression in the parenthesis evaluates to true, statement 1 is executed otherwise
statement 2 is executed.
Flowchart:
Example
x=8
if x>0:
print(x)
else:
print(x+2)
Output:
Example:
x=-8
if x>0:
print(x)
else:
print(x+2)
Output:
-6
In this case the output will be -6 since the test expression evaluates to false. (x+2= -8+2=-6)
n=int(input("enter a number"))
if n>0 :
print("Positive")
else:
print("Negative")
Python also provides a branching structure called the if....... elif statement which is used when the
program requires to check for multiple expressions. There are a number of test expressions followed by
statements.
Syntax
if test expression_1:
statement(s)
elif test expression_2:
statement(s)
elif test expression_3:
statement(s)
elif test expression_4:
statement(s)
.....
.....
else:
statement(s)
Explanation:
The first test expression_1 is evaluated , if it is true, the statement following the if is executed, if it is false,
the test expression_2 following the elif is evaluated. If test expression_2 is true, the statement following it
is executed, if it is false, the next elif test expression is evaluated and so on. Once a test expression
evaluates to true, the statement following it is executed and the control comes out of the elif statement.
So in effect only one of the statement or set of statements is executed.
Example
city="Delhi"
if city=="London":
print ("England")
elif city=="Sydney":
print ("Australia")
elif city=="Delhi"
print("India")
else:
print("Not Selected")
Output
India
In the above code the print statement following the matching elif ie, 'Delhi' is executed and thus the
output will be India.
Sample program: Input the salary of an employee and display the Grade accordingly
#Program to input salary and display corresponding grade of employee
if Salary>25000:
print("Grade I")
elif Salary>15000:
print("Grade II")
elif Salary>9000:
print("Grade III")
else:
print("Grade IV")
1. The initialization expression initializes the loop variable with some legal value.
2. The test expression determines whether or not the loop is to be continued. It is actually the
condition that is checked and depending upon its value (true or false) the loop is executed or
terminated.
3. The update expression is used to change the value of the loop variable for further iteration.
while test-expression:
statement(s)
The test expression or condition following while can be any valid expression including a
variable ,value or the result of a comparison. This condition determines the number of times the loop
executes.
An example:
After the update, control goes back to the beginning of the loop where the test expression is again
evaluated. If it is true the loop is executed and if it is false the control comes out of the loop. The
loop is executed until the test expression evaluates to false. So the above loop will produce the
following output:
1
2
3
4
Test-expression Explanation
The loop iterates till the test expression returns true. It breaks when the expression becomes false.
More examples
Example code
x=0
while x:
print("Loop In")
print("Loop Out")
Output:
Loop Out
Example code
p,q=2,6
while p<q:
print ("Number is",p*q)
p+=1
print (p,q)
Output:
number is 12
number is 18
number is 24
number is 30
66
Sample program: Print the first n integers, where n is input by the user
n=int(input("Enter a positive number :"))
i=1
while i<=n:
print(i)
i+=1
The for loop is another iterative control structure. The for loop executes over a sequence of values
specified by either a string, list, tuple or dictionary or we can use the range function. We shall study
the for loop with lists, tuples and dictionary in later chapters.
The syntax :
where
1. variable is the loop control variable which takes a value in the sequence/list/string
2. sequence specifies is a list of values through which the loop control variable iterates
Example :
for i in "Good":
print(i)
Output:
G
o
o
d
Example:
Output:
2
5
7
9
The range() function is used to specify the sequence of numbers through which a for loop control
variable iterates.
Example:
for a in range(6):
print(a)
Output:
0
1
2
3
4
5
Example:
for x in range(2,6):
print(x)
Output:
2
3
4
5
We can also specify an interval between two values in a range. This is done using the optional step
argument.
The general syntax of the range function is:
where
1. start specifies the beginning of the sequence. It is 0 by default i.e. if we do not mention
explicitly
2. stop specifies where to stop. If n is the stop value, numbers till n-1 will be generated
3. step specifies an integer by which the start value increments/decrements. It is the update
statement. Default value is 1
Given below is a table with examples of range function and the values generated
Example Program : Program to find sum and average of numbers between 1 and n.
#Program to print the sum and average of all numbers from 1 to n, where n is input by the user
n=int(input("enter a number"))
sum=0
for i in range(1,n+1):
print(i)
sum+=i
print('hai')
for i in range(1,11):
print(8+89+1)
Python allows to use one loop within another just like the statements in a loop body.
The syntax for a nested while loop is :
while test-expression:
statement(s)
while test-expression :
statement(s)
Example
1 x=1
2 while x<=4: #Outer while loop
3 y=1 #body of outer loop begins
4 while y<=2: #inner (nested) loop
5 print(y) #body of inner loop begins
6 y+=1 #inner loop body ends
7 x+=1 #outer loop body ends
8 print("Out of Loops")
Working :
Line Program flow
1 Initializes x to 1
2 Outer loop, test expression is evaluated; x<4 if true control goes to line 3 else it goes to line 8
3 Initializes y to 1.
4 Inner loop, test expression is evaluated; y<2, if true control goes to line 5 else it goes to line 7
5 Prints value of y
6 Increments y by 1 (update expression). Control goes back to line 4
7 Increments value of x by 1 (update expression). Control goes back to line 2
For each value of outer loop, the inner loop iterates completely. Thus in the above example for each value of x,
two values of y i.e. 1, 2 will be printed.
Output:
1
2
1
2
1
2
1
2
Example
for i in range(3)
for j in range(2)
print(i*j)
Workflow:
Output:
0
0
0
1
0
2
while i < 3:
n=1
sum=0
while n <= 5:
m=int(input("Enter marks"))
sum = sum + m
n=n+1
i=i+1
Example:
for i in range(1,7): # i iterates from 1 to 7
if i % 3 == 0:
break #loop terminates when number(i) is divisible by 3
print("Square is ", i ** 2) # prints the square of i
print("Loop Over")
Output:
Square is 1
Square is 4
Loop Over
Explanation :
The print statement is executed till the value of i is 2. When the if expression becomes true, the control
comes out of the loop to the line after the loop.
Workflow
The figure below depicts the working of the above loop:
The continue statement
The continue statement simply skips the current iteration of the loop and control goes back to the top of the
loop. This means that the code after continue statement is skipped.
Example:
Output:
Square is 1
Square is 4
Square is 16
Square is 25
Loop Over
Explanation :
The print statement is executed for all values of i except 3. When the if expression becomes true, the control
oes to the top and i is assigne
Using break and continue in nested loops
The break statement in a nested loop brings the control out of the immediate loop. The example below
illustrates this.
i=1
while i<4:
x=1
while x<6:
if x%3==0:
break #when x becomes divisible by 3 the inner loop breaks, control goes to the outer loop
print (i,":",x)
x+=1
print("Outer") #when the inner loop breaks this statement of outer loop is executed
i+=1
Output:
1:1
1:2
Outer
2:1
2:2
Outer
3:1
3:2
Outer
Another example demonstrating the working of a break statement in outer loop.
i=1
while i<7:
if i%3==0: #Loop breaks when i becomes divisible by 3, control goes to statement after loops
break
x=1
while x<6:
print (i,":",x)
x+=1
print("Outer")
i+=1
print("Out of loops")
In the above example the outer loop iterates only till the value of i is 2. The inner loop iterates 5 times for each
value of i.
Output:
1:1
1:2
1:3
1:4
1:5
Outer
2:1
2:2
2:3
2:4
2:5
Outer
Out of loops
The loop else statement
There is an optional else statement in Python loops.
The syntax is :
while test-expression:
statement(s)
else:
statement(s)
This else statement executes only when the loop terminates normally. This means it executes when
a test expression in a while loop evaluates to false or when the for loop variable has completed
all the iterations. It does not get executed when a loop is forced to terminate with
a break statement.
i=1
while i<8:
if i%6==0:
print ("I=", i)
i=i+1
else:
print("Else executed")
print ("Loop ends")
Output:
I= 6
Else executed
Loop ends
i=1
while i<8:
if i%6==0:
break
print ("I=", i)
i=i+1
else:
print("Else executed")
print ("Loop ends")
Output:
I= 1
I= 2
I= 3
I= 4
I= 5
Loop ends
Example:
list2=[i for i in range(4) ]
print(list2)
Output:
[0, 1, 2, 3]
Example:
list2=[i for i in range(25) if i % 2==0]
print(list2)
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
Example:
Output:
['h', 'u', 'm', 'a', 'n', 'e']
Example:
str1=input("Enter a word :")
list1=[i for i in str1 if str1.isupper()]
print(list1)
Output:(option 1)
Enter a word :GOOD MORNING
['G', 'O', 'O', 'D', ' ', 'M', 'O', 'R', 'N', 'I', 'N', 'G']
Output:(option 2)
Enter a wordGood Morning
[]
STRINGS
Strings can be defined as a collection or sequence of character data enclosed in
quotes. The quotes can enclose numbers, characters, symbols etc.. We have seen string
literals in earlier chapters. Now lets take a look at how strings work in Python
Declaring a string
We can declare a string by simply assigning a variable to a string literal
str="PyPlot"
This statement declares a string named PyPlot. It is stored in the memory in contiguous
locations. The figure below shows the memory representation of a string:
A string is stored as an array with index values. In python a string can be indexed in
both directions. So for a string with n characters the indexing would be like:
To print a character we can refer to it using the index value. The format is:
string-variable[index value]
Example:
>>> str="PyPlot"
>>> print(str[2])
P
>>> print(str[-4])
P
>>> print(str[-2])
o
>>> print(str[5])
t
>>>
In the above example the statement print(str[2]) and print(str[-4]) will both print 'P'.
Traversing a String
Example:
str1="Community"
for i in str1:
print(i)
Output:
C
o
m
m
u
n
i
t
y
Operations on Strings
There are a number of specific operations which can be carried out on strings. Lets
discuss each in detail.
Concatenating Strings
The + operator can be used to concatenates strings. When applied to string literals or
variables, it returns the strings joined together.
Example 1:
>>> str1="Hello"
>>> str2="Python"
>>> print(str1+str2)
HelloPython
Example 2: To add space in between the words we can concatenate a space bar
enclosed in quotes:
>>> str1="Hello"
>>> str2="Python"
>>> print(str1+" " +str2)
Hello Python
Example 3:
>>> str1="Hello"
>>> str2="Python"
>>>str3="Interesting"
>>> print(str1+" "+str2+" is "+str3)
Hello Python is Interesting
Example 4:
>>> str="Rollno"
>>> print(str+2)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print(str+2)
TypeError: must be str, not int
This is a very common mistake made by programmers.
Example :
>>> str="Well"
>>> str*2
'WellWell'
Sub strings in strings: Membership Operators
There are two operators in Python which check whether a given sub string is a part of
the string or not. These are 'in' and 'not in'.
The 'in' operator returns true if the sub string is a part of the string and false if not.
The 'not in' operator returns true if the sub string is NOT a part of the string and false if
it is,
Examples:
>>> str="Python Pandas"
>>> "on" in str
True
>>> "pan" in str
False
>>> "Pandas" in str
True
>>> " " in str
True
>>> "o" in str
True
>>> "Py" not in str
False
>>> "h" not in str
False
>>> "B" not in str
True
>>> "daas" not in str
True
String Slicing
String slicing in Python refers to the process of extracting a sub string from a string. We
can obtain a string of characters specified by two index values.
Thus for a string str, the expression str[m:n] returns a portion of the string starting at
index m and upto n-1.
Example
Consider the string , “PERFORMANCE” ,:
>>> str="PERFORMANCE"
>>> str[3:6]
'FOR'
Example :
>>> str[-9:-2]
'RFORMAN'
Variations in slicing
If the first index is omitted the slice starts at the beginning that is the first character.
Therefore, str[0:n] is equivalent to str[ :n].
Example:
>>> str[:7]
'PERFORM'
If the second index is omitted the slice starts at m the beginning index and continues till
the end of the string.
Example:
>>> str[4:]
'ORMANCE'
Also we can use indices to complement two parts of a string. This means that for a string,
str, of length n and any integer x which is more than 0 but less than n(0<=x<=n),
str[:x+str[x:]=str.
Example:
str="Python strings"
I>>> str[:4]+str[4:]
'Python strings'
>>> str[:5]+str[5:]
'Python strings'
A string can also be sliced in steps, i.e, we can specify the interval between two indices.
This is done by adding a third index followed by a : in the expression. This is known as a
stride or step.
Syntax:
string[beg:end:step]
Example:
>>> str="Macedonia"
>>> str[1:8:2]
'aeoi'
The slicing will start from index value 1, i.e the letter 'a'. Since the step is 2, it will skip
the adjacent character and the next letter will be 'e'. Similarly , 'o' and 'i' will be chosen.
Thus the slice will finally be 'aeoi'.
We can also use negative values for STEP. In this case the beginning index value will be
larger than the ending index value.
Example:
>>>str="Python Pandas"
>>>str[11:2:-2]
'anPnh'
Comparing Strings
Strings can be compared using the relational operators (<,>,<=, >=, ==,!=)
>>> str1="Good"
>>> str2="Goat"
>>> str1<str2
False
>>> str1!=str2
True
The strings "Good" and "Goat" are compared character by character.the third letter is
different in the strings. But since the ASCII code of 'o' is greater than 'a' , therefore str1
is larger than str2.
More examples:
str1="Book"
str2="book"
print(str1<str2)
print(str1==str2)
This is not possible as strings are immutable in Python. This means we cannot change
any part of the string or modify it.
Example:
>>> str="PyhtonPAndas"
>>> str[6]='t'
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
str[6]='t'
TypeError: 'str' object does not support item assignment
Python has a large array of in built string methods. The list is exhaustive so we shall
discuss here a few of these.
The general syntax to invoke these functions is
string-object.function()
Case Conversion
1. capitalize()
This function capitalizes the first letter of the string while all other letters are converted
to lowercase.
Example:
2. lower()
Returns the string converted to lowercase.
Example:
3. upper()
Returns the string converted to uppercase.
Example:
>>> str="This is #YEAR 2019"
>>> str.upper()
'THIS IS #YEAR 2019'
4. swapcase()
Converts the uppercase letters to lowercase and vice versa
Example:
>>> str="GREAT this is Awesome!!"
>>> str.swapcase()
'great THIS IS aWESOME!!'
Note: The non character literals are left as it is, i.e they do not change when we apply
these methods.
5. title()
Converts a string to title case by capitalizing the first character of each word in a string.
Example:
>>> str="this is Great News"
>>> str.title()
'This Is Great News'
>>>
1. replace()
This function replaces a part of the old string with a new string.
Syntax :
string.replace(old string/substring, new string/substring)
Example:
>>> str="Hello Friends"
>>> str.replace("Hello", "Good")
'Good Friends'
Note: The replace function does not make any changes to the string. The changes are
only displayed.
>>> str="Hello Friends"
>>> str.replace("Hello", "Good")
'Good Friends'
>>> print(str)
'Hello Friends'
>>>
2. count()
Syntax:
string.count(sub string)
Example:
>>> str="This is Study zone"
>>> str.count("is")
2
We can also use slicing to specify the beginning and ending of the string to restrict the
search for the substring within the main string.
Example:
>>> str="Python programming on windows"
>>> str.count("on", 6,15)
0 #prints 0 as the substring "on" does not occur in the specified start and end
positions
>>> str.count("on",6,25)
1 #prints 1 as the substring occurs only once between 6 and 25
3. find()
This function/method checks whether a sub string is present in a string. If the sub string
is found, the index value of the first letter of the substring is returned otherwise the
value -1 is returned.
Syntax:
string.find(substring)
Example:
>>> str="Casablanca"
>>> str.find("sabl")
2
The above command returns the starting index value of the substring, "sabl".
We can also restrict the search by specifying start and end values in the main string.
>> str.find("a",1,5)
1 #returns the index value of the first occurence of "a" within the string
>>> str.find("Ca",0)
0
4. index()
This functions works exactly like the find() function except it invokes an exception or
error when the sub string is not present in the main string.
Syntax:
string.index(substring)
Example:
>>> str="Casablanca"
>>> str.index("sabl")
2
>>> str.index("ball")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
str.index("ball")
ValueError: substring not found
5. split()
The function splits a string into substrings. The function contains optional arguments,
sep and maxsplit.
Syntax:
string.split(sep=None, maxsplit=-1)
sep specifies the character which is used to identify where to split the strings and
maxsplit specifies the maximum number of splits to be applied to the string.
Example:
6. partition()
This method searches for the string specified in the brackets and then returns a tuple
having three elements. The first is the part before the string, the second is the specified
string and the third is the part after the string.
Syntax:
string.partition(specified string/string variable)
Example:
7. strip()
This method returns the string after removing both the leading and trailing spaces.
There is an optional parameter chars, which can be used to specify the a set of
characters to be removed from left or right of the string.
Syntax:
string.strip([chars])
Output:
Good morning
Good morning
Example(using char):
str=" odshoo omoo do tod "
print(str.strip(' od ')) # removes the characters 'od' from the left and right of the
string along
#with spaces
Output:
shoo omoo do t
8. lstrip()
It returns a copy of the string with the leading spaces(left) removed.
Syntax:
string.lstrip([char])
This function also has an optional parameter char which removes specified characters
from the left along with the spaces .
Example:
str=" odshoo omoo do tod "
print(str.lstrip()) # removes leading spaces only
print(str.lstrip(' od ')) # removes the characters 'od' along with leading spaces
Output:
odshoo omoo do tod
shoo omoo do tod
9. rstrip()
It returns a copy of the string with the trailing spaces(right) removed.
Syntax:
string.rstrip([char])
This function also has an optional parameter char which removes specified characters
from the right along with the spaces.
Example:
str=" odshoo omoo do tod "
print(str.rstrip()) # removes trailing spaces only
print(str.rstrip(' od ')) # removes the characters 'od' along with trailing spaces
Output:
odshoo omoo do tod
odshoo omoo do t
1. isalnum()
This checks whether the target string consists of alphanumeric characters. It evaluates
to true in this case otherwise returns false.
Example:
>>>str="Xyz234"
>>>str.isalnum()
True
>>>str="ABC##90"
>>>str.isalnum()
False #contains special characters "##"
>>>str=" "
>>>str.isalnum()
False #str is an empty string
2. isalpha()
This function checks whether the string consists of alphabets. It returns true if yes and
false if it contains any other character(other than an alphabet)
Example:
>>>str="Collection"
>>>str.isalpha()
True
>>>str="Collection18"
False
3. isdigit()
Checks whether the given string contains of digits. It returns true if all the characters in
the string are digits, false otherwise.
Example:
>>>str="9923"
>>>str.isdigit()
True
>>>str="9934B"
>>>str.isdigit()
False
4. istitle()
Checks whether the string is in title case. If only the first letter(alphabet) of every word
in the string is in uppercase and the rest are in lowercase, it returns True otherwise it
returns False.
Example:
>>>str="Return the Text book"
>>>str.istitile()
False
5. isupper()
Checks whether each letter of a string is in uppercase. If all the letters are in uppercase,
it returns True, False otherwise.
Example:
>>>str="POLLEN"
>>>str.isupper()
True
>>>str=FallEn"
>>>str.isupper()
False
6. islower()
Determines whether the characters of the string are in lowercase. It returns True if
every character/letter of the string is in lowercase, False otherwise.
Example:
>>>str="decathlon"
>>> str.islower()
True
7. isspace()
Example:
>>> str="Good Morning"
>>> str.isspace()
False
Built in functions
These are similar to methods. They are invoked without using the object in the call
statement
1. chr()
Example:
>>> chr(9)
'\t'
>>> chr(65)
'A'
>>> chr(98)
'b'
>>> chr(110)
'n'
>>> chr(22)
'\x16'
>>> chr(40)
'('
2. len()
Example:
>>> str="Hello Patrick"
>>> len(str)
13
3. ord()
This function returns the numeric value represented by a character. It converts the
character to its equivalent numeric value.
Example:
>>>ord('a')
97
>>>ord('"')
34
1.startswith()
This function returns True if the string starts with a specified value, otherwise False.
Syntax
string.startswith(value, start, end)
Here:
value is the value that is being checked with which the string starts (for in the
given
string, string)
start is an optional integer parameter which when used specifies the position
to start
the search
end is an optional integer parameter which when used specifies the position
to end
the search
Example:
>>> str="Education is the key to Success"
>>> str.startswith("Education")
True
Another Example:
>>>str="Education is the key to Success"
>>>str.startswith("Education", 1,9)
False
>>>str.startswith("Education", 0,9)
True
2. endswith()
This function returns True if the string ends with a specified value, otherwise False.
Syntax:
string.endswith(value, start, end)
Here:
value is the value that is being checked with which the string ends( for in the
given string, string )
start is an optional integer parameter which when used specifies the position
to start
the search
end is an optional integer parameter which when used specifies the position
to end
the search
Example:
>>>str="Precious stones are rare"
>>>str.endswith("rare")
True
string=input("Enter a String")
k=len(string) #calculating length of string
t=k//2
flag=True #Boolean variable to determine if fl
i=0 #to mark first letter (starting index)
j=k-1 #to mark last letter
for m in range(t): #iterating loop till half the string length
if string[i]!=string[j]: #comparing the string character by character using indices
flag=False #even if one letter mismatches, flag is set to false
i=i+1
j=j-1
if flag==True:
print("Palindrome")
else:
print("Not a Palindrome")
Explanation
1. Take two indices, one from beginning of string, one from end; i and j
2. Set a Boolean variable flag to True which assumes string to be palindrome
3. Run loop till half of the string is traversed
4. Compare first element and last element, then second and second last and so on till
we reach halg of the string
5. If even one character does not match, set flag to False
6. Display appropriate message depending on value of flag
METHOD: 2
Quiz
Assignment
Quick Revise
Python Editor
Output:
Enter the marks 90
The frequency of marks 90 is: 4
A list is a data type in Python defined by comma separated objects enclosed in square
brackets. Examples of Lists are :
a=[2,4,6,8]
Type=['PAN', 'LAN', 'MAN', 'WAN']
x=[]
marks=[65.5,78.9,56.4,79.5, 96.5,60.0]
The order of list names and names2 do not match therefore they are not equal and
comparison gives a False. On the other hand the order in list n is the same as in names
thus comparison generates a True.
>>> a=[20,40,60,80.90,56]
>>> b=['cat', 'bat','mat','rat']
a contains a list of integers whereas b contains a list of strings. But a list can also
contain values of different types .
Example:
>>> x=[1,'cat',45.6,'A']
>>> print(x)
[1, 'cat', 45.6, 'A']
>>>y=[22,'garden',True, 90.9]
The items or elements in a list may be repeated. Also the list can contain any number of
elements or objects.
Just like Strings, lists can be accessed using index values. The index values can be
positive(left to right) or negative( right to left).
list-variable[index value]
Example:
>>>no=[10,20,30,40,50,60,70]
Memory representation:
>>>no[4]
50
>>>no[-2]
60
>>>a=['cat', 'bat','mat','rat']
Memory Representation:
>>>a[1]
'Bat'
>>>a[-4]
'Cat'
List Operations
Slicing
Just like strings, lists can also be sliced. We can use positive as well as negative indices.
The syntax for slicing a list is :
>>> a=[10,20,30,40,50,60]
>>> a[2:4]
[30, 40]
>>> a[:4]
[10, 20, 30, 40]
>>> a[2:]
[30, 40, 50, 60]
>>> a[-6:-1]
[10, 20, 30, 40, 50]
Example
>>> a=[10,20,30,40,50,60]
>>>a[5:2:-2]
[60, 40]
In this case the starting index has to be larger than the ending index.
In the example below an empty list is returned as the starting index is less than the
ending index and the step is negative.
>>> a[1:4:-1]
[]
A list can be reversed by using the slicing operation with empty starting and ending
index values and a step with the value -1.
>>> a=[10,20,30,40,50,60]
>>> a[ : : -1]
[60, 50, 40, 30, 20, 10]
Lists are Mutable
Lists are one of the few data types which are mutable in Python. Unlike strings, we can
change the elements of a list.
>>>a=[20,25,30,35,40,45]
>>>a[2]=38
>>>a
[20,25,38,40,45]
In the above example we are modifying a single list element. But we can modify multile
elements as can be seen in the following sections.
Example:
>>> a=[10,20,30,40,50,60]
>>> a[0:2]=['Cat','Bat'] #Replacing elements 0 to 1 in the list a, thus 10, 20
will be replaced
>>> a
['Cat', 'Bat', 30, 40, 50, 60] #Modified List
Example:
>>> a=[10,20,30,40,50,60]
>>> a[2:6]=['j', 'k', 'l', 'm', 'n'] #Replacing elements 2 to 5
>>> a
[10, 20, 'j', 'k', 'l', 'm', 'n'] #Modified List
>>> x=[1,2]
>>> x[2:]="456"
>>> x
[1, 2, '4', '5', '6']
The above list, x, is being appended by the sequence "456". Thus '4','5' and '6' are
added to the list after the value 2. Also , x[2:] specifies the starting position where the
new sequence is to be placed.
But when we try to add a number as below:
>>> x[4:]=789
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
x[4:]=789
TypeError: can only assign an iterable
This happens because 789 is a number not a sequence. On the other hand if we use
indexes way out of range, the sequence is just appended at the end of the list as a
sequence.
>>> x=[2,3,4,5,6,7,8,9]
>>> x[20:]="1122"
>>> x
[2, 3, 4, 5, 6, 7, 8, 9, '1', '1', '2', '2']
Traversing a List
Traversing means visiting each element of the list. We can traverse a Python list using
loops.
Example:
a=[20,40,50,60]
for i in a:
print(i)
Output:
20
40
50
60
Example:
a=["Cat","Bat","Rat","Mat"]
for i in a:
print(i)
Output:
Cat
Bat
Rat
Mat
Sample Program : In a list of numbers multiply all even elements by 2 and all
odd elements by 3
a=[20,45,43,78,90,24]
for i in a:
if i%2==0:
i=i*2
else:
i=i*3
print(i)
Sample Output:
40
135
129
156
180
48
a=["Cat","Bat","Mat","Rat"]
found=False
search=input("Enter a word to be searched :")
for i in a:
if i==search:
print("Found")
found=True
if found==False:
print("Not Found")
>>> list1=[89,99,78,65,90,34]
>>> max(list1)
99
>>> min(list1)
34
Similarly:
>>> letters=['h','A','E','r']
>>> max(letters)
'r'
>>> min(letters)
'A'
Sorting
Sorting is arranging the data elements in a particular order. The values in list can either
be arranged in ascending or descending order.
Consider following list of integers as the marks obtained by 7 students in a test:
3, 12, 6, 8, 5, 9, 15
After sorting the list elements appear as :
3, 5, 6, 8, 9, 12, 15
There are a number of ways to sort a given list of elements. A number of algorithms
have been devised to sort list of elements. Depending on the size of the list, each
sorting technique offers a unique solution to sorting a list of values. In the context of
this course we will be studying following sorting algorithms:
1. Bubble sort
2. Insertion sort.
Bubble Sort
In this technique, two adjacent elements in a list are compared. Depending on the
required order of sorting(ascending or descending), the two numbers are swapped. If
the sorting is to be done in ascending order; if first number is bigger than the first, they
are swapped. Similarly in descending order if the second element is larger than the first
element both are swapped. The entire list is traversed and the same technique is
applied, As a result, after the first iteration(pass) of the list the largest(or smallest)
element in the list id bubbled out. to the end of the list.
The entire list is traversed repetitively till all the elements are sorted.
1. START
2. DECLARE TWO VARIABLES M AND N
3. INITIALIZE N=0,
4. INITIALIZE M=0
5. SET A VARIABLE L= Length of the list, L=len(list)
6. If list[M]>list[M+1] THEN SWAP VALUE OF list[M] with list[M+1]
7. SET M=M+1
8. IF (M<L-1) GOTO STEP 4
9. SET N = N +1
10. IF N<L GOTO STEP 3
11. STOP
12.
#Bubble Sort
13.
14. list=[14,56,8,22,78,6] #list to be sorted
15. n=len(list)
16. for i in range(n) #traversing list
17. for j in range(0,n-1) #traversing sublist
18. if list[j]>list[j+1]
19. list[j],list[j+1]=list[j+1], list[j] #swapping
20. print("After Sorting", list)
Quiz
Assignment
Quick Revise
Python Editor
marks=[56,78,87,90,78,90,87,90,45,89,56,90,65,79,97,98] #List of given marks
number=int(input("Enter the marks")) #marks to be input
freq=0 #counter set to 0
for i in marks:
if i==number:
freq=freq+1 #for each occurrence of the number increment counter by
1
print("The frequency of marks", number , " is:", freq)
Output:
Enter the marks 90
The frequency of marks 90 is: 4
A list is a data type in Python defined by comma separated objects enclosed in square
brackets. Examples of Lists are :
a=[2,4,6,8]
Type=['PAN', 'LAN', 'MAN', 'WAN']
x=[]
marks=[65.5,78.9,56.4,79.5, 96.5,60.0]
The order of list names and names2 do not match therefore they are not equal and
comparison gives a False. On the other hand the order in list n is the same as in names
thus comparison generates a True.
>>> a=[20,40,60,80.90,56]
>>> b=['cat', 'bat','mat','rat']
a contains a list of integers whereas b contains a list of strings. But a list can also
contain values of different types .
Example:
>>> x=[1,'cat',45.6,'A']
>>> print(x)
[1, 'cat', 45.6, 'A']
>>>y=[22,'garden',True, 90.9]
The items or elements in a list may be repeated. Also the list can contain any number of
elements or objects.
Just like Strings, lists can be accessed using index values. The index values can be
positive(left to right) or negative( right to left).
list-variable[index value]
Example:
>>>no=[10,20,30,40,50,60,70]
Memory representation:
>>>no[4]
50
>>>no[-2]
60
>>>a=['cat', 'bat','mat','rat']
Memory Representation:
>>>a[1]
'Bat'
>>>a[-4]
'Cat'
List Operations
Slicing
Just like strings, lists can also be sliced. We can use positive as well as negative indices.
The syntax for slicing a list is :
>>> a=[10,20,30,40,50,60]
>>> a[2:4]
[30, 40]
>>> a[:4]
[10, 20, 30, 40]
>>> a[2:]
[30, 40, 50, 60]
>>> a[-6:-1]
[10, 20, 30, 40, 50]
We can also use strides or steps to access the list elements in a particular sequence.
The code above; a[0:4:2] will display the list items starting from index value 0 till value
3[4-1]. The number 2 indicates the step or stride which means that items will be
displayed after skipping the adjacent value. Therefore the values of a[0] and a[2] will
be displayed as indicated below.
We can have negative steps as well.
Example
>>> a=[10,20,30,40,50,60]
>>>a[5:2:-2]
[60, 40]
In this case the starting index has to be larger than the ending index.
In the example below an empty list is returned as the starting index is less than the
ending index and the step is negative.
>>> a[1:4:-1]
[]
A list can be reversed by using the slicing operation with empty starting and ending
index values and a step with the value -1.
>>> a=[10,20,30,40,50,60]
>>> a[ : : -1]
[60, 50, 40, 30, 20, 10]
Lists are one of the few data types which are mutable in Python. Unlike strings, we can
change the elements of a list.
>>>a=[20,25,30,35,40,45]
>>>a[2]=38
>>>a
[20,25,38,40,45]
In the above example we are modifying a single list element. But we can modify multile
elements as can be seen in the following sections.
Example:
>>> a=[10,20,30,40,50,60]
>>> a[0:2]=['Cat','Bat'] #Replacing elements 0 to 1 in the list a, thus 10, 20
will be replaced
>>> a
['Cat', 'Bat', 30, 40, 50, 60] #Modified List
Example:
>>> a=[10,20,30,40,50,60]
>>> a[2:6]=['j', 'k', 'l', 'm', 'n'] #Replacing elements 2 to 5
>>> a
[10, 20, 'j', 'k', 'l', 'm', 'n'] #Modified List
Consider the following statements.
>>> x=[1,2]
>>> x[2:]="456"
>>> x
[1, 2, '4', '5', '6']
The above list, x, is being appended by the sequence "456". Thus '4','5' and '6' are
added to the list after the value 2. Also , x[2:] specifies the starting position where the
new sequence is to be placed.
But when we try to add a number as below:
>>> x[4:]=789
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
x[4:]=789
TypeError: can only assign an iterable
This happens because 789 is a number not a sequence. On the other hand if we use
indexes way out of range, the sequence is just appended at the end of the list as a
sequence.
>>> x=[2,3,4,5,6,7,8,9]
>>> x[20:]="1122"
>>> x
[2, 3, 4, 5, 6, 7, 8, 9, '1', '1', '2', '2']
Traversing a List
Traversing means visiting each element of the list. We can traverse a Python list using
loops.
Example:
a=[20,40,50,60]
for i in a:
print(i)
Output:
20
40
50
60
Example:
a=["Cat","Bat","Rat","Mat"]
for i in a:
print(i)
Output:
Cat
Bat
Rat
Mat
Sample Program : In a list of numbers multiply all even elements by 2 and all
odd elements by 3
a=[20,45,43,78,90,24]
for i in a:
if i%2==0:
i=i*2
else:
i=i*3
print(i)
Sample Output:
40
135
129
156
180
48
a=["Cat","Bat","Mat","Rat"]
found=False
search=input("Enter a word to be searched :")
for i in a:
if i==search:
print("Found")
found=True
if found==False:
print("Not Found")
Try yourself :Program to search for a given word(input by the user )in a list .
Joining lists using the '+' operator.
>>> L1=[2,4,6,8]
>>> L2=[1,3,5,7]
>>> L1+L2
[2, 4, 6, 8, 1, 3, 5, 7]
Lists need not be stored in a variable to be concatenated. We can also join list literals
using the '+' operator.
>>> ['Bat','Rat']+['Pat','Cat']
['Bat', 'Rat', 'Pat', 'Cat']
>>> [22.5,89]+['pot','bot']
[22.5, 89, 'pot', 'bot']
>>> [22.5,89]+['pot','bot']+[False,90]
[22.5, 89, 'pot', 'bot', False, 90]
>>>L1=[2,4,6,8]
>>> L1*2 #Multiplying the list by 2
[2, 4, 6, 8, 2, 4, 6, 8] #The list is displayed twice
>>> ['Bat','Rat']*4
['Bat', 'Rat', 'Bat', 'Rat', 'Bat', 'Rat', 'Bat', 'Rat']
>>> [1,2,3,4]>[2,3,4,5] #the elements of list on the left are smaller than the
one on right
False
>>> ['cat','bat','mat','rat']==['bat','mat','rat','cat']
False #Even if both the list contain same words, the
placement matters
>>> ['cat','bat','mat','rat']>['bat','mat','rat','cat']
True
To be able to compare two lists using relational operators, the elements in the list must
be of the same datat type..
>>> [13,'cat',60.5,22]>['bat',22,34.5,2]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
[13,'cat',60.5,22]>['bat',22,34.5,2]
TypeError: '>' not supported between instances of 'int' and 'str'
Built in functions
There are a number of built in functions which can be used with lists. Let us discuss
each one in detail.
1. append()
Syntax:
list. append(object)
The function append() is used to add a single item at the end of the list.
>>>x=[1,2,3,4]
>>>x.append(7)
>>> print(x)
[1, 2, 3, 4, 7]
The element is added at the end of the list by modifying it, no new list is created.
Strings can be appended in a similar way as a single entity.
>>> a=['cat','mat','rat']
>>> a.append('bat')
>>> a
['cat', 'mat', 'rat', 'bat']
The append function adds the argument at the end of the existing list as a single entity.
This means if we try to append a list using this method, the list will be added at the end
as a single element.
For example:
>>> a=[1,2,3]
>>> a.append([6,7,8]) # appending a list of numbers
>>> a
[1, 2, 3, [6, 7, 8]] # The list is appended as a single item
When we try to append more than one item as separate entities, we get an error.
>>> a.append(6,7,8)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a.append(6,7,8)
TypeError: append() takes exactly one argument (3 given)
2. extend()
Syntax:
list.extend(iterable)
The extend() method can be used to concatenate two lists. The second list is added at
the end of the first list.
>>> m=[1,2,3]
>>> m.extend([5,6,7])
>>> m
[1, 2, 3, 5, 6, 7]
>>> m=[1,2,3]
>>>n=[8,9,4]
>>> m.extend(n)
>>> m
[1, 2, 3, 8, 9, 4]
3. insert()
This function inserts a new value in the list at a given postion.
Syntax:
list.insert(index, value)
index is the position in the list where the new value is to be inserted.
The rest of the items in the list are pushed to the right.
Example:
>>> a=[2,4,7]
>>> a.insert(2,90)
>>> a
[2, 4, 90, 7]
>>> a.insert(1,"Good")
>>> a
[2, 'Good', 4, 90, 7]
>>> a.insert(3,[2,3,4])
>>> a
[2, 'Good', 4, [2, 3, 4], 90, 7]
4. reverse()
Syntax:
list.reverse()
This function simply reverses a list, by changing the order of the elements in a list.
Example:
>>> a=[22,44,56,11,99, 88]
>>> a.reverse()
>>> a
[88, 99, 11, 56, 44, 22]
5. index()
Syntax:
list.index(item)
This function returns the index value of the first occurrence of an item in the list.
Example:
>>> city=["Delhi","Mumbai","Chennai","Kolkatta"]
>>> city.index("Mumbai")
1
If there are more than one occurrences of an item , the index value of the first
occurrence only will be returned.
>>> list=[2,3,4,2,5,6]
>>> list.index(2)
0
6. sort()
Syntax:
list.sort()
Example:
>>> a=[22,44,56,11,99, 88]
>>>a.sort()
>>> a
[11, 22, 44, 56, 88, 99]
7. len()
Syntax:
len(list)
Example :
>>> a=[22,44,56,11,99, 88]
>>>print(len(a))
6
8. count()
Syntax:
list.count(element)
This function returns the number of occurrences of a particular element in the list.
Example:
>>> y=[22,66,77,44,66,88,99,22]
>>> y.count(22)
2
>>> y.count(99)
1
>>> y.count(38)
0
>>> y.count(-99)
0
9. clear()
Syntax:
list.clear()
Example:
>>> y=[22,66,77,44,66,88,99,22]
>>>y.clear()
>>> y
[]
10. remove()
Syntax:
list.remove(object)
This function removes an object specified in the brackets, from the list.
Example:
>>> x=[2,4,5,2,7,9,8,9]
>>> x.remove(8) #to remove number 8 from the list
>>> x
[2, 4, 5, 2, 7, 9, 9]
>>> Fruits=["Apple","Mango","Guava","Orange","Papaya"]
>>> print(Fruits)
['Apple', 'Mango', 'Guava', 'Orange', 'Papaya']
>>> Fruits.remove("Guava")
>>> Fruits
['Apple', 'Mango', 'Orange', 'Papaya'] #the remove statement removes
"Guava" from the list
If we try to use the remove() an object which does not exist, an error occurs.
>>> Fruits.remove("Kiwi")
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
Fruits.remove("Kiwi")
ValueError: list.remove(x): x not in list
11. pop()
Syntax:
list.pop(index)
The method also removes an item whose index value is mentioned from the list. It is
different from the remove method in two ways; it deletes the element whose index
value is mentioned , and it returns the item which is deleted.
>>> Fruits.pop(3)
'Papaya'
>>>Fruits
['Apple', 'Mango', 'Orange']
If we use the pop function without the index value, the last element in the list will be
removed.
Example:
>>> Fruits.pop()
'Orange'
>>> Fruits
['Apple', 'Mango']
The pop() function when used with out of range index will give an error.
Example:
>>> x=[2,4,5,2,7,9,8,9]
>>> x.pop(9)
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
x.pop(9)
IndexError: pop index out of range
Example:
>>> x=[2,4,6,8,9,13]
>>> x.pop(-1)
13
Searching in a List
Searching a value:
Suppose we need to search for a value in a list. For this we can use the in operator.
Example:
>>> list1=[89,99,78,65,90,34]
>>> max(list1)
99
>>> min(list1)
34
Similarly:
>>> letters=['h','A','E','r']
>>> max(letters)
'r'
>>> min(letters)
'A'
With character data type the list values are compared using the ASCII code.
Bubble Sort
In this technique, two adjacent elements in a list are compared. Depending on the
required order of sorting(ascending or descending), the two numbers are swapped. If
the sorting is to be done in ascending order; if first number is bigger than the first, they
are swapped. Similarly in descending order if the second element is larger than the first
element both are swapped. The entire list is traversed and the same technique is
applied, As a result, after the first iteration(pass) of the list the largest(or smallest)
element in the list id bubbled out. to the end of the list.
The entire list is traversed repetitively till all the elements are sorted.
1. START
2. DECLARE TWO VARIABLES M AND N
3. INITIALIZE N=0,
4. INITIALIZE M=0
5. SET A VARIABLE L= Length of the list, L=len(list)
6. If list[M]>list[M+1] THEN SWAP VALUE OF list[M] with list[M+1]
7. SET M=M+1
8. IF (M<L-1) GOTO STEP 4
9. SET N = N +1
10. IF N<L GOTO STEP 3
11. STOP
Code:
Insertion Sort
In this type of sorting, the list is divided into two parts, the sorted and
unsorted part. The first element from the unsorted sub list is inserted into
the correct position in the sorted sub list.
This is repeated till the entire of the list is sorted.
The following example illustrates how the insertion sort algorithm works:
Code :
#Insertion Sort
list=[24,56,7,89,90,11]
k=len(list)
for i in range(1, k):
numd = list[i]
j = i-1
while j >=0 and numd < list[j] :
list[j+1] = list[j]
j -= 1
list[j+1] = numd
Example:
list2=[i for i in range(4) ]
print(list2)
Output:
[0, 1, 2, 3]
Example:
list2=[i for i in range(25) if i % 2==0]
print(list2)
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
Example:
list1=[i for i in 'humane']
print(list1)
Output:
['h', 'u', 'm', 'a', 'n', 'e']
Example:
str1=input("Enter a word :")
list1=[i for i in str1 if str1.isupper()]
print(list1)
Output:(option 1)
Enter a word :GOOD MORNING
['G', 'O', 'O', 'D', ' ', 'M', 'O', 'R', 'N', 'I', 'N', 'G']
Output:(option 2)
Enter a wordGood Morning
[]
Python Tuples
Table of Contents
Tuples: Introduction
Creating a Tuple
Traversing Tuples
Deleting a Tuple
Tuple Operations
Concatenation
Replicating Tuples
Membership Operators
Nesting Tuples
Tuple Slicing
Using Relational Operators with Tuples
Built in Tuple Methods
len()
max()
min()
index()
count()
any()
sum()
tuple()
sorted()
Sample Programs
Quick Revise
Python Editor
Tuples are a data structure in Python similar to a list. There are two basic differences:
1. Tuples are enclosed in round(()) brackets,
2. Tuples are immutable(cannot be changed) unlike lists.
Tuples consist of elements separated by a comma. The values in a Tuple may be of the
same or different types. All the operations performed on a list also apply to tuples
except operations that insert, update and delete elements from a tuple.
Examples of Tuples:
Creating tuples
A tuple can be created by simply assigning a comma separated list of values enclosed
in round brackets to an identifier.(brackets are optional)
>>>MyTuple= tuple()
>>>pritn(MyTuple)
()
>>>T1=tuple(24,56,"Good","Deed")
>>>print(T1)
(24,56,"Good","Deed")
Traversing a Tuple
We can traverse or visit each element of a tuple using a loop.
Example:
>>> t=("Preeti","Anamika", "Aditya", "Paalguni","Paru", "Aditya", "Aditya", "Kartik",
"Pulkit","Aditya")
>>> for i in t:
print(i)
Preeti
Anamika
Aditya
Paalguni
Paru
Aditya
Aditya
Kartik
Pulkit
Aditya
Example:
>>> x=(22,44,11,77,88,99,33,66,99)
>>> l=len(x)
>>> for i in range(l):
print(x[i])
22
44
11
77
88
99
33
66
99
Deleting a Tuple
To delete a tuple, we can simply use the del statement.
Example:
>>> x=(22,44,11,77,88,99,33,66,99)
>>> del x
>>> x
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
x
NameError: name 'x' is not defined
Tuple Operations
Example:
>>> t1=(24,78,65)
>>> t2=(22.4,56,7)
>>> t1+t2
(24, 78, 65, 22.4, 56, 7)
>>> s1=("Good","Bad","Ugly")
>>> s2=("A1","B2","c3")
>>> s1+s2
('Good', 'Bad', 'Ugly', 'A1', 'B2', 'c3')
The + operator requires both the operands to be of type tuple. We cannot simply add
values without brackets as we could do in lists.
Example 3:
>>> t1+(45)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
t1+(45)
TypeError: can only concatenate tuple (not "int") to tuple
Example:
>>> ("Good", "Exciting")*2
('Good', 'Exciting', 'Good', 'Exciting')
3. Tuple Membership
The in and not in operators can be used to check if a value is present in a tuple or not.
Example(in):
>>> t1=("Open", 90, 'J', 45.56)
>>> 90 in t1
True
>>> "Good" in t1
False
Example(not in):
>>> "Cool" not in t1
True
>>> 45.56 not in t1
False
Nesting Tuples
We can create a tuple by embedding existing tuples. This is known as nesting of tuples.
Example:
>>> t1=(9,4)
>>> t2=(22,(t1))
>>> t2
(22, (9, 4))
Examples:
>>> t1=(20,30,40,50,60,70)
>>> print(t1[2:4])
(40, 50)
>>> t2[2:9:2]
'to r'
>>> t2=(34,44,55,66,77,88)
>>> t2[::1]
(34, 44, 55, 66, 77, 88)
>>> t2[2:]
(55, 66, 77, 88)
>>> t2[2::]
(55, 66, 77, 88)
>>> t2[:4:]
(34, 44, 55, 66)
>>> t2[4:0:-1]
(77, 66, 55, 44)
Tuples can be compared using the operators, >, <, ==, !=, <=,>=. Python compares
the tuples element by element.
Examples:
>>> t1=(22,33,44,55,66,77)
>>> t2=(25,35,45,65,75,85)
>>> t1>t2
False
>>> t2>t1
True
>>> t1=(90,20)
>>> t2=(20,90)
>>> t1>t2
True
>>> t2>t1
False
>>> t1==t2
False
>>> t1!=t2
True
>>>t1=("Good","Ugly")
>>> t3=(22,44)
>>> t1>t3
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
t1>t3
TypeError: '>' not supported between instances of 'str' and 'int'
Tuples having elements of different data types can however be compared. the elements
are compared one at a time. In the example below the numbers 22 and 44 are
compared first followed by the strings.
Example:
>>> t1=(22,"Hello")
>>> t2=(44, "Ugly")
>>> t1>t2
False
However such comparison is nly possible if both the tuples have elements of similar
data types in the same order.
Example:
>>> t1=(22,"Hello")
>>> t3=("Good",67)
>>> t1<t3
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
t1<t3
TypeError: '<' not supported between instances of 'int' and 'str'
In the example above the position of the number and the string values are not same
within the tuple. Thus comparing these two will generate an error.
1. len()
Returns the number of elements in the tuple.
Example:
>>>t1=(1,”Preeti”,90,”XII-C”)
>>>len(t1)
4
2. max()
Returns the element with the maximum value in a tuple
Example:
>>>t1=(90,22,45,44,88,99)
>>>max(t1)
99
This is possible only if all the elements of the tuple are of the same data type otherwise,
an error will be generated.
Example:
>>> t1=(22,"Hello")
>>> max(t1)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
max(t1)
TypeError: '>' not supported between instances of 'str' and 'int'
3. min()
Returns the element with the minimum value in a tuple
Example:
>>>t1=(90,22,45,44,88,99)
>>>min(t1)
22
The same rule applies to the min() function, it returns minimum value only if all the
elements are of the same datatype
4. index()
Returns the positional value of an element in the tuple. Indexing starts at 0.
>>> t1=(22,33,44,55,66,88)
>>> t1.index(44)
2
The index function returns an error if the given element is not in the list:
>>> t1=(22,33,44,55,66,88)
>>> t1.index(90)
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
t1.index(90)
ValueError: tuple.index(x): x not in tuple
5. count()
It is used to count the number of occurrences of an item in the tuple.
Example:
>>> t=("Preeti","Anamika", "Aditya", "Paalguni","Paru", "Aditya", "Aditya", "Kartik",
"Pulkit","Aditya")
>>> t.count("Aditya")
4
6. any()
This checks if the tuple is non empty. It means it returns True if there is at least if item
in the tuple. It returns false if the tuple is empty.
Example:
>>>t=(45,)
>>>any(t)
True
>>>t=()
>>>any(t)
False
7. sum()
The sum() function returns the sum of all the lements in a tuple. The elements need to
be of the same data type.
Example:
>>> t1=(90,35,89,22)
>>> print(sum(t1))
236
Also the sum function can be used for only numeric values. Adding non-numeric values
generate an error.
Example:
>>> print(sum(t2))
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print(sum(t2))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
8. tuple()
The tuple() function is use to convert a list into a tuple.
Example:
>>> list1=["Hello", 90,"Renting",99.99]
>>> print(tuple(list1))
('Hello', 90, 'Renting', 99.99)
9. sorted()
This is a very interesting function. It sorts a tuple and returns a list after sorting. The
original tuple remains as it is i.e. the sequence of elements does not change in it.
Example:
>>> t=("Preeti","Anamika", "Aditya", "Paalguni","Paru", "Aditya", "Aditya", "Kartik",
"Pulkit","Aditya")
>>> sorted(t)
['Aditya', 'Aditya', 'Aditya', 'Aditya', 'Anamika', 'Kartik', 'Paalguni', 'Paru', 'Preeti', 'Pulkit']
Assignment-1
Assignment-2
Quiz
Quick Revise
Python Editor
Introduction
Dictionaries are a way of representing arrays with keys in Python. It can be considered as an
unordered list of items with each element referenced by a key.
Features of Dictionaries:
1. They are mutable, ie the values may change , although the keys cannot be changed.
2. They may grow or shrink, ie elements can be added or deleted as required.
3. The elements are referenced by a key.
4. Each key in a dictionary has to be unique.
We can say that a dictionary is an unordered list of items where every item is a key-value pair.
Defining a dictionary
We can define a Python dictionary using a series of key-value pairs enclosed in curly brackets.
Representation of D:
1. By directly assigning comma separated key-value pairs enclosed in a pair of curly braces to a
valid identifier.
The statement below creates a dictionary d1, having four elements all of the same type.
The following statement creates a dictionary having 4 fractional values with keys from 1 to 4.
>>> d={1:3.14, 2:2.67, 3:4.88, 4:6.90}
>>> d
{1: 3.14, 2: 2.67, 3: 4.88, 4: 6.9}
In the statement below we can see that the dictionary is created with 6 elements with two values of
type string.
>>> d={1:3.14, 2:2.67, 3:4.88, 4:6.90, 5:"Hearty Brown", 6:"5 ft 6 in"}
>>> d
{1: 3.14, 2: 2.67, 3: 4.88, 4: 6.9, 5: 'Hearty Brown', 6: '5 ft 6 in'}
>>>d=dict()
>>>d
{}
We can create an empty dictionary by assigning a pair of empty curly brackets to an identifier.
>>>d={}
>>>d
{}
>>> d={}
>>> d[1]="Rat"
>>> d[2]="Bat"
>>> d[3]="Mat"
>>> d[4]="Cat"
>>> d
{1: 'Rat', 2: 'Bat', 3: 'Mat', 4: 'Cat'}
Sample Program :
Write a Python script to generate and print a dictionary that contains a number as the key and its
square as the value in the form(x:x*x). The dictionary should contain n elements where n is input by
the user.
Example if n = 4, then the dictionary should look like :
{1: 1, 2: 4, 3: 9, 4: 16}
Accessing dictionaries
1. To access the individual elements, we can use the key value enclosed in square brackets.
>>> print(d[1])
Rat
>>> for i in d:
print(i)
1
2
3
4
#Prints the keys of the dictionary corresponding to the value of i (loop iterator).
>>> for i in d:
print(d[i])
Rat
Bat
Mat
Cat
#Prints the values of the dictionary corresponding to the keys represented by value of d[i].
>>> for i in d:
print(i,":",d[i])
1 : Rat
2 : Bat
3 : Mat
4 : Cat
We can also use some built in functions with loops to access the elements of a dictionary, a. We
shall cover this a bit later on this page.
1. Adding elements: We can add elements to a dictionary, ie key-value pair using simple
assignment.
>>> d['Stream']='Science'
>>> d
{1: 'Amrit', 2: 'Bhavesh', 3: 'Chetan', 4: 'Dinesh', 5: 'Kartikay', 'Stream': 'Science'}
2. Updating elements: We can update existing elements in a dictionary by simple using the
assignment operator. For example to change the value of the element referenced by the key 4 to
'Falguni', we can write the following command:
>>> d[4]='Falguni'
>>> d
{1: 'Amrit', 2: 'Bhavesh', 3: 'Chetan', 4: 'Falguni', 5: 'Kartikay'}
Note: To change or update an element in a dictionary, we can assign a value to an existing key. But
if the key is not present in the dictionary, a new element , the key-value pair is added to the
dictionary.
>>> d[6]='Prerna'
>>> d
{1: 'Amrit', 2: 'Bhavesh', 3: 'Chetan', 4: 'Falguni', 5: 'Kartikay', 6: 'Prerna'}
Sample program:
WAP to add records to a dictionary 'fruits' .
Operators and built in Dictionary methods
1. in and not in: These membership operators check whether a given element belongs to the
dictionary or not, respectively.
Example :
>>>d={1: 'Amrit', 2: 'Bhavesh', 3: 'Chetan', 4: 'Falguni', 5: 'Kartikay', 6: 'Prerna'}
>>> 2 in d
True
When we use in or not in to check for the presence of a value with dictionary name , the key is
checked. The value only is not checked and we get the answer as false even if it is present in the
dictionary.
Example:
>>> 'Prerna' in d
False #No key
To check for a value in the dictionary, we need to use the values() function.
Example:
>>> 'Prerna' in d.values()
True
2. len()
This function returns the number of elements i.e. the key-value pairs present in the dictionary.
>>> len(d)
6
3. d.items()
This function returns the list of elements in the dictionary.
>>> list(d.items())
[(1, 'Amrit'), (2, 'Bhavesh'), (3, 'Chetan'), (4, 'Falguni'), (5, 'Kartikay'), (6, 'Prerna')]
4. d.keys()
This function returns the all the keys that are present in the dictionary.
Example:
>>> d.keys()
dict_keys([1, 2, 3, 4, 5, 6])
5. d.values()
This returns all the values in the dictionary.
Example:
>>> d.values()
dict_values(['Amrit', 'Bhavesh', 'Chetan', 'Falguni', 'Kartikay', 'Prerna'])
6. d.get(key)
This function returns the value corresponding to a key in the dictionary. If the key is not present, the
function returns, 'None'.
>>> d.get(2)
'Bhavesh' #It returns the name 'Bhavesh' corresponding to the key, 2.
We can also specify a default value to be displayed in case the key is not present in the dictionary.
7. d.update(object)
Here object can be a dictionary or an iterable with a key-value pair
Example:
>>> d4={2:"Jayesh", 9:"Sameeksha"}
>>> d.update(d4) #adding a new dictionary
>>> d
{1: 'Amrit', 2: 'Jayesh', 3: 'Chetan', 4: 'Falguni', 5: 'Kartikay', 6: 'Prerna', 7: 'Lara', 8: 'Lori', 9:
'Sameeksha'}
Here since the key 2 already exists in the dictionary, the name is changed to Jayesh. Also the pair
9:"Sameeksha" is added since it does not exist in the dictionary.
8. d.clear()
This function clears the entire dictionary. It deletes all the key-value pairs.
9. d.pop(key)
This function removes a key along with its value in a dictionary.
>>> d2.pop(2)
'Ball'
>>> d2
{1: 'Apple', 3: 'Pineapple', 4: 'Mangoes'}
>>> d2.pop(1)
'Apple'
>>> d2
{3: 'Pineapple', 4: 'Mangoes'}
If we try to remove a non existent key from the dictionary, an exception is generated.
>>> d2.pop(6)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
d2.pop(6)
KeyError: 6
We can provide with a default value which will be displayed if the key we pop is not in the dictionary.
>>> d2.pop(6,-1)
-1
Thus the value -1 will be returned if we try to pop a non existent key.
10. popitem()
This function removes the last element inserted from a dictionary. It also returns the removed key value
pair.
Example:
d2={1:"Bat",2:"Cat",3:"Rat",4:"Mat"}
print(d2)
d2.popitem() #the last key value pair i.e. 4:"Mat" is
removed
print(d2)
Output:
{1: 'Bat', 2: 'Cat', 3: 'Rat', 4: 'Mat'}
{1: 'Bat', 2: 'Cat', 3: 'Rat'}
The elements are deleted in a LIFO (Last In First Out) manner i.e, the element which is inserted first is
deleted first.
11. del
This(del) is actualy statement that can be used to remove a key value pair from a dictionary.
Example:
d={1:"GATE",2:"GRE", 3:"CAT", 4:"ASL"}
print(d)
The function will generate an error if we try to use it with a non existent key.
Example:
d={1:"GATE",2:"GRE", 3:"CAT", 4:"ASL"}
del d[6]
print(d)
Output:
Traceback (most recent call last):
File "C:/Users/Neeru/AppData/Local/Programs/Python/Python38-32/d1.py", line 3, in <module>
del d[6]
KeyError: 6
where:
sequence is a list of values which represent the keys
value parameter provides the value to be given to all the keys. It can be single value or a list of values..
The fromkeys() method creates a new dictionary from a given sequence of elements and values.
The sequence can be a tuple or list containing values. these form the keys of the dictionary. The
value parameter is optional but if provided assigns the given value to the keys obtained from the
sequence.
Example:
x=(1,2,3,4)
y=20
d1=dict.fromkeys(x,y)
print(d1)
Output:
{1: 20, 2: 20, 3: 20, 4: 20}
in the above example the keys are formed from the iterable x and all the keys are assigned the value
given by 20. We can also assign a list of values to the keys.
Example:
x=[1,2,3,4]
y=(20,25,60,65)
d1=dict.fromkeys(x,y)
print(d1)
Output:
{1: (20, 25, 60, 65), 2: (20, 25, 60, 65), 3: (20, 25, 60, 65), 4: (20, 25, 60, 65)}
13. copy()
The copy() function creates a shallow copy of an existing dictionary. This means that the original
dictionary does not get changed if we make changes to the copied one.
Example:
d1={1:"Bat",2:"Cat",3:"Rat",4:"Mat"}
d2=d1.copy()
print(d2)
print(d1)
Output:
{1: 'Bat', 2: 'Cat', 3: 'Rat', 4: 'Mat'} #d2 is a copy of d1
{1: 'Bat', 2: 'Cat', 3: 'Rat', 4: 'Mat'} #d1 is printed
Example:
d1={1:"Bat",2:"Cat",3:"Rat",4:"Mat"}
d2=d1.copy()
d2.pop(2) # removing key value 2
print(d2)
print(d1)
Output:
{1: 'Bat', 3: 'Rat', 4: 'Mat'}
{1: 'Bat', 2: 'Cat', 3: 'Rat', 4: 'Mat'} # no change to d1
Example:
d1={'Name':"Victoria", 'Age':65, 'City':"London", 'MStatus':"Married"}
d2=d1
print(d2)
Output:
{'Name': 'Victoria', 'Age': 65, 'City': 'London', 'MStatus': 'Married'}
The = operator creates a deep copy of the dictionary. this means that changes made to the copy are
reflected back to the original dictionary.
Example:
d1={'Name':"Victoria", 'Age':65, 'City':"London", 'MStatus':"Married"}
d2=d1
print(d2)
d2.pop("MStatus") #removing a key value
pair
print(d1) # printing original
Output:
{'Name': 'Victoria', 'Age': 65, 'City': 'London', 'MStatus': 'Married'} #copied Dictionary
{'Name': 'Victoria', 'Age': 65, 'City': 'London'} # original Dictionary after
changes
14. setdefault()
The method setdefault() is used to return the value of a key which exists in the dictionary. If the key
does not exist then the setdefault() function inserts the key with the given value.
Example:
furniture = {"Name": "Chair", "Model": "Rocking Chair", "Material": "Wood"}
x = furniture.setdefault("Model", "Rocking Chair")
print(x)
print(furniture)
Output:
Rocking Chair
{'Name': 'Chair', 'Model': 'Rocking Chair', 'Material': 'Wood'}
Output:
Dark Brown
{'Name': 'Chair', 'Model': 'Rocking Chair', 'Material': 'Wood', 'color': 'Dark Brown'} #the key-value is
added
15. max()
The max() function is used to find the key with the maximum value in a dictionary. It uses the key get
function.
Example:
Output:
Friends
16. min()
The min function retrieves the key with the lowest value in a dictionary.
Example:
IMDb = {'The Umbrella Academy' : 8.0,'Friends':9.8, 'Stranger Things':8.8, "Russian Doll":8.0}
lowest = min(IMDb, key=IMDb. get)
print(lowest)
Output:
The Umbrella Academy
NOTE: If we have more than 1 key with lowest(or highest) value in a dictionary then the value first
occurrence is printed.
17. sorted()
The sorted() function can be used to sort a dictionary by value ,by key or by key value pair using the
various in built dictionary methods.
Sorting by key
When applied using the dictionary keys() function the sorted() method returns the data in a dictionary
in ascending order of the keys. The values of corresponding to the keys are not changed.
Example:
d1={4:"Apple", 1:"Oranges",3:"Plum", 2:"Grapes"}
print(sorted(d1.keys()))
Output:
[1, 2, 3, 4]
Sorting by value
The sorted() function when used with the values() method of dictionary returns the values in a
dictionary in ascending order.
Example:
d1={4:"Apple", 1:"Oranges",3:"Plum", 2:"Grapes"}
print(sorted(d1.values()))
Output:
['Apple', 'Grapes', 'Oranges', 'Plum']
Example:
d1={4:"Apple", 1:"Oranges",3:"Plum", 2:"Grapes"}
print(sorted(d1.items()))
Output:
[(1, 'Oranges'), (2, 'Grapes'), (3, 'Plum'), (4, 'Apple')]
In all the above scenarios the sorted function returns the values of the dictionary in a sorted
manner . However the dictionary is not sorted.
Example:
d1={4:"Apple", 1:"Oranges",3:"Plum", 2:"Grapes"}
print(sorted(d1.items()))
print(d1)
Output:
[(1, 'Oranges'), (2, 'Grapes'), (3, 'Plum'), (4, 'Apple')] # sorted values are returned and
printed
{4: 'Apple', 1: 'Oranges', 3: 'Plum', 2: 'Grapes'} # original dictionary is not changed
Example:
d1={4:"Apple", 1:"Oranges",3:"Plum", 2:"Grapes"}
d2=sorted(d1.items()) # storing the sorted value in the second
dictionary print(d2)
Output:
[(1, 'Oranges'), (2, 'Grapes'), (3, 'Plum'), (4, 'Apple')]
Example:
d1={4:"Apple", 1:"Oranges",3:"Plum", 2:"Grapes"}
print(sorted(d1.items(), reverse=True))
Output:
[(4, 'Apple'), (3, 'Plum'), (2, 'Grapes'), (1, 'Oranges')]
Sample Program:
Write a Python script to search for a given value in a Dictionary.
Sample Program:
WAP to count the number of elements in a dictionary.
Programs
Python Modules
Table of Contents
Modular Programing
Using Modules
The math module
The random module
random()
randint()
randrange()
The Statistics module
mean()
median()
mode()
Modular Programming
Modular programming refers to the breaking of large programs into smaller manageable pieces of code
or modules. They are referred to by user defined names.
Python Modules consist of lines of Python code that perform a specific task. They help in modularizing
programs. Modules can be of three types in Python:
1. Inbuilt modules
2. Functions (Inbuilt and User Defined)
3. Packages
In this chapter we shall be covering Python inbuilt modules. Python offers numerous modules that contain
functions which perform specific tasks. We can also say that a group of functions that perform specific
category of tasks are grouped together to form a Python module. For example the math module contains
functions that perform mathematical calculations.
In the context of this chapter we shall be covering three main modules viz math, random and statistics
module.
Using a Module
We can use the import statement in three ways to be able to use functions from a particular module.
1. import <module-name>
For example, in order to find the square root of a given number, we can use the sqrt() function from the math
module, we can write the following code:
import math
x=int(input("Enter a number"))
print(math.sqrt(x))
Output:
Enter a number 81
9.0
We can also use the following two ways to import modules and use the functions they contain:
Example:
from math import sqrt
print(sqrt(81))
Output:
9.0
Example:
from math import *
print(sqrt(81))
Output:
9.0
Note that in the first method we need to specify the module name followed by the function name in order to
use the function.
Math module
The math module contains functions that can be used to perform mathematical tasks. Given below is the list of
functions i the math module.
Random module
This module contains functions to generate random numbers between two values. Among other uses the
random module can be used
Using the random module
1. random()
This function generates a random number between 0.0 and 1.0(not including) . It des not accept any argument
in the brackets.
Example:
import random
print(random.random())
Output:
0.7489153508852794
In order to get a larger number or use it as part of a larger calculation, we can multiply it by an integer.
Output:
7.168087410165594
2. randitn(x,y)
The randint() function accepts two arguments and generates a random number between the two. For example if
the arguments are x and y it will generate an integer value between x and y.
Example:
import random
print(random.randint(2,7)) #will generate a number between 2 and 7, inclusive
Output:
2
We can also use the randint() function to generate and assign a random number to a variable. For example;
p=randint(9,11), will assign a value between 9 and 11 to the variable p.
The randint() function can be implemented in numerous ways.
Example:
Consider the code below:
import random
y=random.randint(4,9) #y will be assigned a value between 4 and 9
for i in range(1,y+1): # depending on the value of y, the loop will run from 1 to n where 4<=n<=9
print(i, end=" ")
In the above code y can have value between 4 and 9. Thus the loop will run from 1 to n, n being in the range
4-9. Thus we can have any one of the following outputs in this case:
option 1: 1 2 3 4
option 2: 1 2 3 4 5
option 3: 1 2 3 4 5 6
option 4: 1 2 3 4 5 6 7
option 5: 1 2 3 4 5 6 7 8
option 6: 1 2 3 4 5 6 7 8 9
import random
x=random.randint(2,4)
y=random.randint(4,7)
for i in range(x,y+1):
print(i, end=" ")
There are two random numbers generated in the above code, x and y. The minimum and maximum values that
the variables x and y will assume are as follows:
| x | y
_________________
min | 2 | 4
_________________
max | 4 | 7
Thus the loop will give output starting with anything between 2 - 4 and ending between 4-7.
3. randrange (x,y,z)
This function also generates a random integer between x and y-1. There is also a step value, z which has a
default value of 1. Also the step parameter is optional.
Example:
import random
y=random. randrange (4,21,2) # y will be assigned value between 4 and 20 which are even as step is 2. So it
can be
#4,6,8,10,12,14,16,18,20
print(y)
Output:
18
Example:
import statistics
list1=[3,4,20,7,9,8]
print(statistics.mean(list1))
Output:
8.5
In the above code the numbers in the list are are added and then divided by 6 to give average or mean.
2. median()
The function median() returns the middle value in a list of given numbers/data by first arranging them in
ascending order and then finding the exact middle element.
Example:
import statistics
list1=[3,4, 7,9,8] #when ordered, the list will be; 3,4,7,8,9 and the middle is 7
print(statistics.median(list1))
Output:
7
If the list contains even numbers then the two middle numbers (after arranging the list) are added and divided
by two to get the median.
Example:
import statistics
list1=[2,15,4,6,8,9] #ordered list will be : 2,4,6,8,9,15 and the middle two values are 6,8. So
median=(6+8)/2=7
print(statistics.median(list1))
Output:
7.0
3. mode()
This function returns the value in a given list that occurs the most number of times.
Example:
import statistics
list1=[2,15,4,6,8,9,4,9,8,4,9,9,7]
print(statistics.mode(list1))
Output:
9
NOTE: If there are more than one values in the list having same number of occurrences, then this function
returns the first number.
Example:
import statistics
list1=[2,15,4,6,8,9,4,9,8,4,9,9,7,4] # 4 and 9 each occur four times in the list
print(statistics.mode(list1))
Output:
4