CH-1 Python Revision
CH-1 Python Revision
Module-1
● Introduction
● Variables &Data Types
● Keywords Expressions
● Operators& Operands
● Input and Output (Python’s Built-in-Functions)
● Comments
● Flow of Execution
Module-2
● Strings
Module-3
● Lists
● Tuples
● Dictionary
--------------------------------------------------------------------------------------------
Introduction
Python (a computer language):
● Python is a powerful and high level language and it is an interpreted
language.
● It is widely used general purpose, high level programming language
developed by Guido van Rossum in 1991.
● Python has two basic modes: interactive and script.In interactive mode
(python.exe/py.exe), the result is returned immediately after pressing the
enter key. In script mode (IDLE), a file must be created and saved before
executing the code to get results.
● Interactive Mode: Interactive mode, as the name suggests, allows us to
interact with OS.
● Script Mode: In script mode, we type Python program in a file and then use
interpreter to execute the content of thefile.
1
Identifiers: An identifier is a name used to identify a variable, function, class,
module, or other object. An identifierstarts with a letter A to Z or a to z or an
underscore ( _ ) followed by zero or more letters, underscores, and digits (0to 9).
Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive
Programming language. Thus, Value and value are two different identifiers
in Python.
Here are following identifiers naming convention for Python:
✔Class names start with an uppercase letter and all other identifiers with a
lowercase letter.
✔Starting an identifier with a single leading underscore indicates by
convention that the identifier is meant to be private.
✔Starting an identifier with two leading underscores indicates a strongly
private identifier.
✔If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
Keywords
Keywords are used to give some special meaning to the interpreter and are used by
Python interpreter to recognize the structure of program. All keywords are in small
alphabets except for False, None and True, which start with capital alphabets.
Dynamic Typing: In Python, while the value that a variable points to has a type,
the variable itself has no strict type
in its definition.
2
• Static Typing: In Static typing, a data type is attached with a variable when it is
defined first and it is fixed.
Variables & Data Types
A variable / object has three main components:
a) Value of the variable / object
b) Identify of the variable /object
c) Type of the variable / object
● A Value:Value is any number or a letter or string. To bind value to a
variable, we use assignment operator (=).
● An identity:Identity of the object is its address in memory and does
not get change once it is created. We may know it by typing id
(variable). We would be referring to objects as variable for now.
● A type: (i.e data type) is a set of values, and the allowable operations
on those values. It can be one of the following:
1. Number: Number data type stores Numerical Values. This data type is
immutable i.e. value of its object cannot be changed. Numbers are of three
different types:
● Integer & Long (to store whole numbers i.e. decimal digits without
fraction part)
● Float/floating point (to store numbers with fraction part)
● Complex (to store real and imaginary part)
● Boolean(results in true & false)
2. None: This is special data type with a single value. It is used to signify the
absence of value/false in a situation. It is represented by None.
3. Sequence: A sequence is an ordered collection of items, indexed by positive
integers. It is a combination of mutable (a mutable variable is one, whose
value may change) and immutable (an immutable variable is one, whose
value may not change) data types. There are three types of sequence data
type available in Python, they are Strings, Lists & Tuples.
3.1 String- is an ordered sequence of letters/characters. They are
enclosed in single quotes (' ') or double quotes ('' "). The quotes are not part of
string. They only tell the computer about where the string constant begins and
3
ends. They can have any character or sign, including space in them. These are
immutable. A string with length 1 represents a character in Python.
3.2 Lists: List is also a sequence of values of any type. Values in the list
are called elements / items. These are mutable and indexed/ordered. List is
enclosed in square brackets ([]).
3.3 Tuples: Tuples are a sequence of values of any type and are indexed
by integers. They are immutable. Tuples are enclosed in ().
4. Sets: Set is unordered collection of values of any type with no duplicateentry.
It is immutable.
5. Mapping: This data type is unordered and mutable. Dictionaries fall under
Mappings.
5.1 Dictionaries: It can store any number of python objects. What
they store is a key -value pairs, which are accessed using key. Dictionary is
enclosed in curly brackets ({}).
4
Object mutability is one of the characteristics that makes Python a dynamically
typed language. Though Mutable and Immutable in Python is a very basic concept,
it can at times be a little confusing due to the intransitive nature of immutability.
Operators& Operands
Operators are special symbols that represent computation like addition and
multiplication. The values that the operator is applied to are called operands.
Operators when applied on operands form an expression. Operators are categorized
as Arithmetic, Relational, Logical and Assignment. Following is the partial list of
operators:
● Mathematical/Arithmetic operators: +, -, *, /, %, ** and //.
● Relational operators: <, <=, >, >=, != or <> and ==.
● Logical operators: or, and, & not
● Assignment Operator: =, +=, -=, *=, /=, %=, **= and //=
● Bitwise Operators
● Membership Operators
● Identity Operators
Type conversion
The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion.
OUTPUT
('datatypeof num_int:', <type 'int'>)
('datatypeof num_flo:', <type 'float'>)
('Value of num_new:', 22.23)
('datatypeof num_new:', <type 'float'>)
Comments
As the program gets bigger and more complicated, it becomes difficult to read it
and difficult to look at a piece of code and to make out what it is doing by just
looking at it. So it is good to add notes to the code, while writing it. These notes
are known as comments. In Python, comments start with '#' symbol. Anything
written after # in a line is ignored by interpreter. For more than one line comments,
we use the following;
● Place '#' in front of each line, or
● Use triple quoted string. ( """ """)
Flow of Execution
Execution always begins at the first statement of the program. Statements are
executed one after the other from top to bottom. Further, the way of execution of
the program shall be categorized into three ways:
(i) Sequence statements, (line by line, one after one)
6
(ii) Selection statements, and (condition, selective, if-else…, elif…)
(iii) Iteration or looping statements.(for, while)
if statement
if statement is the most simple decision making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
Syntax:
ifcondition:
# Statements to execute if
# condition is true
Here, condition after evaluation will be either true or false. if statement accepts
boolean values – if the value is true then it will execute the block of statements
below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:
if condition:
statement1
statement2
7
# Here if the condition is true, if block will consider only statement1 to be inside
its block.
i =10
if(i> 15):
print("10 is less than 15")
print("I am Not in if")
Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if
statement is not executed.
if- else
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do
something
else if the condition is false. Here comes the else statement. We can use
the else statement with if statement to execute a block of code when the condition
is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
8
# python program to illustrate If else statement
i =20;
if(i< 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present
in the if statement is false after call the statement which is not in block(without
spaces).
nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows us
to nest if statements within if statements. i.e, we can place an if statement inside
another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
9
# python program to illustrate nested If statement
i =10
if(i ==10):
# First if statement
if(i< 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if(i< 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
10
# Python program to illustrate if-elif-else ladder
i =20
if(i ==10):
print("i is 10")
elif(i ==15):
print("i is 15")
elif(i ==20):
print("i is 20")
else:
print("i is not present")
Output:
i is 20
Short Hand if statement
Whenever there is only a single statement to be executed inside the if block then
shorthand if can be used. The statement can be put on the same line as the if
statement.
Syntax:
if condition: statement
i =10
ifi< 15: print("i is less than 15")
Output:
i is less than 15
Short Hand if-else statement
This can be used to write the if-else statements in a single line where there is only
one statement to be executed in both if and else block.
Syntax:
statement_when_True if condition else statement_when_False
Example:
11
# Python program to illustrate short hand if-else
i =10
print(True) ifi< 15elseprint(False)
Output:
True
Iterative statements
In some programs, certain set of statements are executed again and again based
upon conditional test. i.e executed more than one time. This type of execution is
called looping or iteration. Looping statement in python is implemented by using
'for' and 'while' statement.
Syntax: (for loop)
for variable in range(start,stop+1,step):
statements
Syntax: (while loop)
while (condition):
Statements
Practical:------------------------------------------------------------------------
Q – 1. Rewrite the following code fragment using if…elif..else statement:
color = input(“Enter the color name:”)
if (color==”red”):
print(“Arun House”)
if(color==”blue”):
print(“Aditya House”)
if(color==”yellow”):
print(“Ravi House”)
if(color==”green”):
print(“Bhaskar House”)
if(color!=”red” or color!=”blue” or color!=”yellow” or color!=”green”)
print(“Not a valid color name!!!!”)
12
Ans.:
color = input(“Enter the color name:”)
if (color==”red”):
print(“Arun House”)
elif(color==”blue”):
print(“Aditya House”)
elif(color==”yellow”):
print(“Ravi House”)
elif(color==”green”):
print(“Bhaskar House”)
else:
print(“Not a valid color name!!!!”)
Q – 2 What will the output of the following code fragment when the input is 7,
5, and 11?
if month>=6 and month<=9:
print(“Term – I”)
elif month>=10 and month>=3:
print(“Term – II”)
else:
print(“Vacation”)
Ans.:
When the input is: 7 Term – I
When the input is: 5 Vacation
When the input is: 11 Term – II
Code:
p = input("Enter any principle amount")
t = input("Enter any time")
if (t>12):
si = p*t*10/100
else:
si = p*t*15/100
print "Simple Interest = ",si
Output:
Enter any principle amount 3000
13
Enter any time12
Simple Interest = 3600
Q.4. Write a program to input any choice and to implement the following.
Choice Find
1. Area of square
2. Area of rectangle
3. Area of triangle
Code:
c = input ("Enter any Choice")
if(c==1):
s = input("enter any side of the square")
a = s*s
print"Area = ",a
elif(c==2):
l = input("enter length")
b = input("enter breadth")
a = l*b
print"Area = ",a
elif(c==3):
x = input("enter first side of triangle")
y = input("enter second side of triangle")
z = input("enter third side of triangle")
s = (x+y+z)/2
A = ((s-x)*(s-y)*(s-z))**0.5
print"Area=",A
else:
print "Wrong input"
Output:
Enter any Choice2
enter length4
enter breadth6
Example: 1. Write a program to input any number and to print all natural
numbers up to given number.
Code:
n = input("enter any number")
14
for i in range(1,n+1):
printi,
Output:
enter any number10
1 2 3 4 5 6 7 8 9 10
2. Write a program to input any number and to find sum of all natural
numbers up to given number.
Code:
n = input("Enter any number")
sum= 0
fori in range(1,n+1):
sum = sum+i
print "sum=",sum
Output:
Enter any number5
sum = 15
3.Write a program to input any number and to find reverse of that number.
Code:
num = int(input("Enter any number") )-----------1234
r=0
while(num>0): ------true
rev=num%10----------remainder will be 4
r = (r*10)+rev-----(0*10)+4=4
num= num//10-------- 1234//10=123
print( "reverse number is", r)------4
Output:
>>> Enter any number345
reverse number is 543
>>>
15
code:
1. sum = 0
fori in range(1,11,2):
sum+ = i
print "sum = ", sum
output:
sum = 25
2. sum = 0
i=4
while (i<=20):
sum+=i
i+= 4
print "Sum = ",sum
output:
Sum = 60
16
Example: Interchange while loop in to for loop.
i=5
s=0
while (i<25):
s+ = i
i+=5
print " Sum =", s
Ans:
s=0
fori in range(5,25,5):
s+=i
print "Sum = ", s
Ans:
i values are 10,15,20,25,30,35,40,45
8 times
2. i=4
while(i<25):
printi
i+=4
Ans:
i values are 4,8,12,16,20,24
6 times
String Manipulation
Introduction to String Manipulation in Python
As you are aware that python allows to use following built-in data types:
1. Numbers
17
2. Strings
3. List
4. Tuple
5. Dictionary
So you have basic ideas about strings. A string data type is representing text values
in the program. If you are accepting anything in single or double or triple quotes in
python is known as a string.
It can be set of letters, symbols or numbers also.
Moreover you are also familiar with input and output operations as well. So let’s
explore the string manipulation in python with some more operators and functions.
Accessing a string through loop
As we have discussed a string is a collection of letters, numbers, and symbols each
entity has its own position in the string. This is called an index. So using by using
these indices you can access the string trough a LOOP.
Accessing a string by its index letter by letter is also known as traversing.
Accessing string through for loop
To access the string letter by letter for loop can be used. Take a look at the
following code:
>>>text = "Tutorial"
>>>forch in text:
print(ch,end="*")
The output will be:
T*u*t*o*r*i*a*l*
Accessing string through the loop using the range function
text = "Tutorial"
>>>forch in range(0,len(text),1):
print(text[ch],end="*")
The output will be:
T*u*t*o*r*i*a*l*
When you want to access the string using range function another built-in function
len() will be used to identify the length of a string.
18
Reverse a string
>>>text ="Tutorial"
>>>P =len(text)
>>>forch in range(-1,(-P-1),-1):
print(text[ch],end="")
The output will be:
lairotuT
String Manipulation in Python using Basic Operators
As you have used basic arithmetic operators + and *
or “addition” and “multiplication” respectively.
These operators can be used for string manipulation in python as well. Here in
string manipulation these operators are known as “concatenation” and
“replication” operator.
String concatenation operator “+”
It is used to join two words. Observe the below given code and output:
>>>text ="Tutorial" + "Computer"
>>>print(text)
The output will be:
TutorialComputer
Valid combinations for + operator:
1. n + n = 3 + 3 = 6
2. s + s = “3” + “3” = 33
Invalid combinations:
1. n + s = 3 + “3”
2. s + n = “3” + 3
String replication operator “*”
It is used to replicate the string number of time as specified in the expression. You
can use number * string or string * number as well.
>>>text ="TutorialComputer"
19
>>>print(2*text,"-->",text*2)
The output will be:
TutorialComputerTutorialComputer -->TutorialComputerTutorialComputer
Valid combination for * operator:
1. n * n = 3 * 3 = 9
2. s * n = “$” * 3 = “$$$”
3. n * s = 3 * “$” = “$$$”
Invalid combinations:
1. s * s = “3” * “3”
Some facts:
1. Numbers combination returns the multiplication.
2. String combination will error in “*” operator.
Note: This operator can operate either string or number only, not both
together.
20
The output will be:
Tutor found
The not in Operator
It is used reversed than “in” operator. Returns True when specified text is not
available in the text, otherwise False.
text ="TutorialComputer"
if "Tutor" not in text:
print("Tutor not found")
else:
print("Tutor found")
The output will be:
Tutor found
Slices in String
Slices are another advanced feature supported by python. It will return the specific
part from given string and ranges. It will take the form of str[n1:n2].
>>>text="TutorialComputer"
>>>print(text[0:5])
Tutor
>>>print(text[3:9])
orialC
>>>print(text[:5])
Tutor
>>>print(text[5:])
ialComputer
>>>print(text[-1:])
r
>>>print(text[:-1])
TutorialCompute
>>>print(text[-5:-4])
I
>>>print(text[1:3:3])
u
21
String methods & built in functions:
len() capitalize() find(sub[,start[, end]]) isalnum() isalpha()isdigit() lower()
islower() isupper() upper() lstrip() rstrip() isspace() istitle() find()
replace(old,new) join () swapcase() partition(sep)
split([sep[,maxsplit]])endswith() startswith() ord() chr()
Example:
>>> s='Congratulations'
>>>len(s)
15
>>>s.capitalize()
'Congratulations'
>>>s.find('al')
-1
>>>s.find('la')
8
>>>s[0].isalnum()
True
>>>s[0].isalpha()
True
>>>s[0].isdigit()
False
>>>s.lower()
'congratulations'
>>>s.upper()
'CONGRATULATIONS'
>>>s[0].isupper()
True
>>>s[1].isupper()
False
>>>s.replace('a','@')
'Congr@tul@tions'
>>>s.isspace()
False
>>>s.swapcase()
'cONGRATULATIONS'
>>>s.partition('a')
('Congr', 'a', 'tulations')
>>>s.split('ra',4)
22
['Cong', 'tulations']
>>>s.split('a')
['Congr', 'tul', 'tions']
>>> a=' abc '
>>>a.lstrip(;.,12dfg)
'abc '
>>>a.rstrip()
' abc'
Examples:
Example: Write a program to input any string and count number of uppercase and
lowercase letters.
Code:
s=input("Enter any String")
int s
u=0
l=0
i=0
whilei<len(s):
if (s[i].islower()==True):
l+=1
if (s[i].isupper()==True):
u+=1
i+=1
print "Total upper case letters :", u
print "Total Lower case letters :", l
Output:
Enter any String Python PROG
Python PROG
Total upper case letters: 5
Total Lower case letters: 5
23
i=0
whilei<len(s):
if (s[i].islower()):
print( s[i].upper(), )
if (s[i].isupper()):
print( s[i].lower(), )
i + =1
Ans:
iNDIANfestivals
24
l = []
In above statement, I have created an empty list named as l. Now whenever I want
to access elements from this list I will use l and then manipulate the list with
different expressions.
Creating lists with multiple values
To create lists with multiple values initialize your list with values you want to put
in the list.
l = [22,33.33,45,’17/08/2001′,’Mital’,’Parmar’]
The list values can be accessed by its index.
IndexValue
0 – l[0] 22
1 – l[1] 33.33
2 – l[2] 45
3 – l[3] 17=/08/2001
4 – l[4] Mital
5 – l[5] Parmar
25
The text initialized with list function returned as a list.
l = list(‘Python Lists’)
print(l)
Output –> [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘ ‘, ‘L’, ‘i’, ‘s’, ‘t’, ‘s’]
Creating list from user input
Use input function to create a list in following manner.
l = list(input(“Enter a value”))
print(l)
Output –>
Enter values:4567
[‘4’, ‘5’, ‘6’, ‘7’]
Observe the output given above, when you take values from input it always returns
the numbers as string with single quotes in a list. To avoid this you can use this.
To do this use eval function and enter values with square brackets:
l = eval(input(“Enter values”))
print(l)
Output–>
Enter values: [4,5,6,7]
[4,5,6,7]
Whenever eval function is used with input you can enter the values in form of list it
self at the input console.
26
<listobject>.<function>()
Some of the library functions not required the alias names.
These functions are:
len()
list()
index()
append()
extend()
insert()
pop()
clear()
count()
remove()
reverse()
sort()
sorted()
27
>>> l=[['Mon','Tue','Wed'],['Thu','fri'],'Sat','Sun']
>>>print(len(l))
The output of the above code is 4, as there are 2 sub lists elements and 2 main list
elements specified in the list.
The list() method
This function will convert the passed parameters into list. If no arguments passed
then it will create an empty list.
Syntax:
list([elements])
Take a look at this code:
>>>list()
It returns [], empty list.
>>>list("Tutorial")
It will return [‘T’, ‘u’, ‘t’, ‘o’, ‘r’, ‘i’, ‘a’, ‘l’] as output.
rno=int(input("Enter the rollno:"))
stu_name=input("Enter the name:")
fees=int(input("Enter the Fees:"))
stu_rec=list([rno,stu_name,fees])
print(stu_rec)
In the above code, three separate elements merged into a list, using list() method.
Similarly you can convert any tuple, dictionary elements into the list using list()
function.
The index() method()
This method returns the matched index of element from the list.
Syntax:
<list_obj>.index(<element>)
28
Observe this code:
>>> l=[11,22,27,34,67,98]
>>>l.index(27)
The above code will return 2 as output. The element value 27 at index 2.
If the number which is not present in the list elements and passed as parameter
python will return as error.
>>> l=[11,22,27,34,67,98]
>>>l.index(2)
The above code raise following error:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
l.index(2)
ValueError: 2 is not in list
The append() method
The append() method will add elements into the existing list. The element which is
added by append() method will add at the end of the list.
Syntax:
<list_obj>.append(<element>)
Have a look at this code:
l=[]
l.append(10)
print(l)
The append() method exactly takes one argument to add the values. The value can
be a scalar value, tuple, list, dictionary, etc.
The extend() method
The extend() method add multiple values into the list.
29
Syntax:
<list_obj>.extend(<element>)
Observe the following code:
l=[]
l.extend([11,22,33,44])
print(l)
The insert() method
As you learn how to add or insert elements into the list at the end using append()
method and extend() method. In this section we will see one more method to
insert() element at desired location.
Syntax:
<list_obj>.insert(<idx>,<element>)
The insert() method takes two parameters:
idx – Index position of the element
Element – Value of needs to be insert
Observe the following code:
l=['Jan','Mar','Apr']
l.insert(1,'Feb')
print(l)
The output will be:
[‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’]
It can also takes a negative index to be inserted.
The pop() method
The pop() is used to remove element from the list.
Syntax:
30
<list_obj>.pop(<idx>)
Look at the following example:
l=['Jan','Feb','Mar','Apr']
l.pop()
print(l)
When the pop() method is used without any parameter, it will delete the last
element.
The output will be:
[‘Jan’, ‘Feb’, ‘Mar’]
You can delete a specific element by passing the index value of that particular
element.
l=['Jan','Feb','Mar','Apr']
l.pop(2)
print(l)
The output will be:
[‘Jan’, ‘Feb’, ‘Apr’]
The remove() method
The remove method is used to remove the elements by its value. If you are not
aware about the index of the element and you know the value, you can use remove
method.
Syntax:
<list_obj>.remove(<element_value>)
Observe this code:
l=['Jan','Feb','Mar','Apr']
l.remove('Feb')
print(l)
The output will be:
31
[‘Jan’, ‘Mar’, ‘Apr’]
The clear() method
It will remove all elements from the list. This function doesn’t require any
parameter.
Syntax:
<list_obj>.clear()
l=['Jan','Feb','Mar','Apr']
l.clear()
print(l)
It will return [] i.e. empty list.
In the next section of python list functions class 11, we will discuss some functions
with common operations of a list.
The count() method
It will count the presence of element passed as an argument from the list. If the
element is not available in the list, it will return zero.
Syntax:
<list_obj>.count(element)
Let us have look at the following code:
l=['Jan','Feb','Mar','Apr','Jan']
l2=l*2
print(l2.count('Jan'))
The reverse() method
It will display the list in the reverse form. It will reverse the list element in place. It
doesn’t require any value as parameter or argument.
Syntax:
<list_obj>.reverse()
32
Look at this code:
l=['Jan','Feb','Mar','Apr']
l.reverse()
print(l)
The sort() method
It sorts the elements in ascending or descending order. The default order is
ascending order.
Syntax:
<list_obj>.sort([reverse=False/True])
The code:
l=['Jan','Feb','Mar','Apr']
l.sort()
print(l)
The output will be:
[‘Apr’, ‘Feb’, ‘Jan’, ‘Mar’]
To display the list in descending order use the reverse parameter and pass it with
the value “reverse=True”.
Observe this code:
l=['Jan','Feb','Mar','Apr']
l.sort(reverse=True)
print(l)
The output will be:
[‘Mar’, ‘Jan’, ‘Feb’, ‘Apr’]
The sorted() method
This function sorted() function also sort the list but it will return a new sorted list.
Observe the following code:
33
l=['Jan','Feb','Mar','Apr']
l1=sorted(l)
print(l1)
Moreover you can also use some of the following functions:
max()
min()
sum()
Accessing/Traversing Lists by Index
List elements are stored with indexes. Each element of lists is having a specific
index like a string. There are two ways to access lists:
- Positive indexing
- Negative Indexing
- Using loop
Positive Indexing
The positive indexing allows to access the value starting with 0,1,2,3 and so on.
l = [11,22,33,44,55]
print("L[0]=>",l[0])
print("L[1]=>",l[1])
print("L[2]=>",l[2])
print("L[3]=>",l[3])
print("L[4]=>",l[4])
Negative Indexing
Negative indexing refers to access or traverse the list from reverse order in means
when the negative index is used, it will display the last element first.
l = [11,22,33,44,55]
print("L[0]=>",l[-1])
34
print("L[1]=>",l[-2])
print("L[2]=>",l[-3])
print("L[3]=>",l[-4])
print("L[4]=>",l[-5])
Using Loop
You can use for loop to access list elements. Observe the following code:
l = [11,22,33,44,55]
fori in range(0,5):
print("L[",i,"]=>",l[i])
I have used range to display the value of i in output, You can avoid range function
as well in following manner:
l = [11,22,33,44,55]
fori in l:
print(i)
Slicing Lists – List manipulation
You can extract specified elements by slicing lists. Consider the following syntax
for slicing lists:
slice1 = l [start : stop : step]
The start refer to the starting index value of list slice and stop refer to the end index
value.
Let’s have a look at the following example:
l = [11,22,33,44,55]
slice1 = l[0:4]
print(slice1)
The negative index value extract the list in reverse order.
l = [11,22,33,44,55]
35
slice1=l[2:-1]
print(slice1)
It will slice the list from index 2 i.e. 33 to index -1 i.e. 44. Hence the output will be
[33,44].
Now just take a look at the following code:
l = [11,22,33,44,55]
slice1=l[2:33]
print(slice1)
In the above code, list slicing is starting with index 1 i.e. 33 to index 33 i.e not
available in the list, hence it will print the rest of all the values. Python executes the
statement without errors.
When both lists are given out of bounds it will return empty lists.
Now let’s have a look at following examples:
l=[11,22,33,44,55,66,77,88,99]
print(l[0:10:2])
The above code slice the lists elements and display alternative index values.
Similarly you can change the step value and slice the list accordingly. Consider
these examples:
l=[11,22,33,44,55,66,77,88,99]
print(l[0:10:3])
print(l[:5:3])
print(l[::3])
print(l[4::2])
Membership Operator – List manipulation
There are two membership operators as we have covered in string manipulations:
- in
- not in
in operator
36
It returns true if the specified number is present in the list.
l=[11,22,33,44,55,66,77,88,99]
print(44 in l)
This code returns True as 44 is present in the list.
not in Operator
The not in Operator results exactly opposite compared to in operator.
l=[11,22,33,44,55,66,77,88,99]
print(44 not in l)
This code returns False as 44 is present in the list.
Concatenation
It is also known as joining lists. To join or concatenate the lists, ‘+’ operator is
used. For example,
l1 = [4,5,6]
l2 = [7,8,9]
l3 = l1 + l2
print(l3)
The above code joins the elements of l1 and l3 into l3. So the output will be
[4,5,6,7,8,9].
Replication
It is use to repeat the list number of times.
l= [1,2,3]
l=l*4
The output of above code is [1,2,3,1,2,3,1,2,3,1,2,3]
Comparing Lists
To compare lists relational operator is used.
37
l1 = [4,5,6]
l2 = [7,8,9]
if l1>l2:
print("L1 is greater than L2")
else:
print("L2 is greater than L1")
It will compare the list values and display the results accordingly.
Making true copy of a list
To make a true copy of a list copy function is used.
l1 = [1,2,3]
l2 =l1.copy()
print(l2)
- Tuples:-A tuple is a sequence of values, which can be of any type and they
are indexed by integer. Tuples are just like list, but we can't change values of
tuples in place. Thus tuples are immutable. The index value of tuple starts
from 0. A tuple consists of a number of values separated by commas.
Creating Tuples
To create tuple, put all the values inside parenthesis i. e. moon or rounded brackets.
You can create tuples in following ways:
1. Empty Tuple – Like empty lists, you can create empty tuples
2. Tuple of integers – Tuple with integer values
3. Tuple of mixed numbers – Tuple with integers, and float numbers
4. Tuple of characters – Tuple using characters
5. Tuple of mixed values – Tuple with numbers, characters and strings
6. Nested Tuple – A tuple which has another tuple as an element
7. Tuple from existing sequence – A tuple can be created using existing
sequence
Empty Tuple
As we have discussed, tuple are created using parenthesis. You can create an empty
tuple like this:
38
t = ()
Where t is a tuple object like variable, = assigns empty values with ().
Tuple of integers
The tuple which has integer values are considered as tuple of integers. The
example is something like this:
t = (2,4,5,6)
You can create a tuple with single element without brackets also. For example,
t = 56, or t=(56,) are similar.
If you write t = (56) then it will consider as a single value, not tuple.
Tuple of mixed numbers
The tuple can have mixed numbers including integers and floating numbers.
Consider the following example:
t = (90,87.50,85.25,3,7.0,45,65)
Tuple of characters
The tuple which contains sequence of characters is considered as tuple of
characters. For example:
t = (‘a’,’b’,’c’,’d’,’e’)
Tuple of mixed values
A tuple can also consists of mixed values including integers, characters and strings.
For example,
t = (1,’Amrita’,95.85,’A’)
Nested Tuple
A tuple can have another tuple as an element is known as nested tuple. Consider
the following example:
t = (1,’Virat Kohli’,(102,67,23))
Tuple from existing sequence
39
As list() method we have used to convert any sequence into the list, similarly
tuple() function allows creating any sequence into the tuple. Let’s have a look at
the following examples:
t = tuple(‘TutorialCOMPUTER’)
output: ('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'C', 'O', 'M', 'P', 'U', 'T', 'E', 'R')
>>>
t = tuple([10,20,30])
output: (10, 20, 30)
>>>
You can use eval() function to create a tuple of values entered by user.
Accessing/Traversing Tuple
1. Indexing
2. Slicing
3. Membership Operator
4. Concatenation
5. Replication
Indexing
As like lists we can access tuples using forward (Positive) Indexing, backward
(negative) indexing, and looping. Look at the following examples:
t = (11,34,56,78,90)
print(t[1],t[3],t[2])
print(t[-1],t[-2],t[-3])
fori in range(len(t)):
print(i)
Slicing
The tuple can be accessed through slicing as like as lists. For example
t = [10,20,30,40,50]
slice1 = t[0:4]
40
print(slice1)
slice1=t[2:-1]
print(slice1)
slice1=t[2:33]
print(slice1)
print(t[0:10:2])
print(t[0:10:3])
print(t[:5:3])
print(t[::3])
print(t[4::2])
Membership Operator
Now you know very well how to use membership operator in and not in for
accessing values from the tuple. Consider following example:
t = [10,20,30,40,50]
print(44 in t)
print(44 not in t)
The first print statement will will display False where as second print statement
will display True as 44 is not present in the tuple.
In the next section of Creation Traversal of Tuples Class 11 we will talk about
tuple concatenation.
Concatenation
It is also known as joining the tuples. Have a look at the following example:
t1 = (4,5,6)
t2 = (7,8,9)
t3 = t1 + t2
print(t3)
41
Replication
You can replicate the entire tuple values using * operator. Look at this example:
t= (1,2,3)
print(t * 4)
Standard Library Methods: -Tuple functions and methods
1. len()
2. max()
3. min()
4. sum()
5. sorted()
len() function
This function returns the length of a tuple. The length of tuple means total number
of elements present in the list.
For example,
t = (22,44,56,78)
print("The tuple contains",len(t), " elements")
max() function
The max function returns the maximum value from the specified tuple.
t=(1,3,5,7,8,4,2)
print(max(t))
In string it will return the highest ordered letter as maximum.
t=('c','b','a','x','u','t')
print(max(t)
This function will only work with tuples having similar data type only. If multiple
datatypes combined in the single tuple and you want to print the max() value this
function won’t work.
min() function
It will returns minimum value from the sequence specified in the tuple.
42
t=(34,56,78,21,33)
print(min(t))
Rest min() will work as max().
sum() function
It will return the sum of values used in the tuple sequence.
t=(34,56,789,99)
print(sum(t))
This function only works with numeric elements.
sorted() function
It will returns the tuple elements in ascending or descending order in form of list.
t=(7,3,4,1,2)
print(sorted(t))
For descending order use reverse=True as another parameter. Have a look at this
code:
t=(7,3,4,1,2)
print(sorted(t, reverse=True))
Tuple Methods or Functions
In this category we are using methods or function with dot symbol. These methods
or functions are as following:
1. tuple()
2. index()
3. count()
4.
tuple() function
As we have seen in the tuple creation, this function convert any sequence of lists
into tuple.
index() function
It will return the index of specified tuple element value.
43
t=(2,5,6,7,8)
print(t.index(6))
The output of above code is 2.
count() function
This function will display number of frequency of elements available in the tuple.
t=(2,3,4,2,3,4,6,7,8,2)
print(t.count(2))
Above code will return 3 as output as 2 is repeated 3 times in the tuple.
Linear search in the tuple
To search in tuple, follow these steps:
1. Start with the leftmost element in the tuple
2. Take one variable to flag the message element found on 1
3. Take a variable to search an element
4. Traverse the tuple using for loop
5. Compare the element with the search element
6. Update the flag variable to 1
7. Outside the loop, print a message element found or not, using if for the flag
variable
def search():
t = (3,4,1,5,6,8)
f=0
n = int(input("Enter the value to search:"))
fori in range(len(t)):
if t[i] == n:
f=1
if f==1:
print("Found")
else:
44
print("Not Found")
Mean of values stored in the tuple
To find the mean of values in tuple, follow the below given steps:
1. Import a package statistics
2. Define the tuple with the values
3. Declare a variable to store the mean of tuple values
4. The mean can be displayed with float value so use round function to restrict
its decimal places
5. Use print to print the final value
Observe the following code:
import statistics
t = (1, 3, 4, 5, 7, 9, 2 )
meanoftuple = round(statistics.mean(t) ,2)
print("Mean is :", meanoftuple)
Output Questions
[1]
t =('t','u','p','l','e')
t = ('Tuple',) + t[3:]
print(t)-- output: ('Tuple', 'l', 'e')
[2]
t1=(78,99,11)
t2=(10,20)
t3=t1+t2*2
t4=t3+t2
print((t1+t2)*2)-- (78, 99, 11, 10, 20, 78, 99, 11, 10, 20)
print(t3)-- (78, 99, 11, 10, 20, 10, 20)
print(t4)- (78, 99, 11, 10, 20, 10, 20, 10, 20)
45
[3]
t1=(55,66,7)
t2=('55','66','7')
print(t1*2)-- (55, 66, 7, 55, 66, 7)
print(t1+t2)-- 55, 66, 7, '55', '66', '7')
[4]
t=(78,67,88,99,11,34,56)
s1=[:3]
s2=[3:3]
s3=[3:]
s4=[-3:3]
s5=[:-3]
s6=[3:-3]
s7=[-3:3]
s8=[:]
s9=[3:-1]
s10=[0:3]
[5]
t = [13,23,43,63,83]
slice1 = t[0:4]
print(slice1)
slice1=t[2:-1]
print(slice1)
slice1=t[2:33]
print(slice1)
46
print(t[0:10:2])
print(t[0:10:3])
print(t[:5:3])
print(t[::3])
print(t[4::2])
[6]
t = (14,34,54,74,94)
ft = (14,34,54,74,94)
fori in range(len(t)):
if i%2==0:
print(i-3,",",end="")-> -3 ,-1 ,1 ,
print()
print(t[-1]+t[-2]+t[-3])
print(t[4]-t[2]-t[0])
Error Questions
[1]
t=(56,89,54,32,12)
t[1]=99
print(t+(4))
print(t[5])
[2]
t1=(55,66,7)
t2=('55','66','7')
47
t3=(4)
print(t1*'2')
print(t1+t2+t3)
[3]
t = (14,34,54,74,94)
fori in range(t):
if i%2==0:
print(t-3,",",end="")
- Dictionary:-
As we have used the English dictionary. It contains different words with its
meanings. In python, the dictionary refers to the mapped items using key-value
pairs. It is a versatile type of python.
A dictionary item doesn’t contain any index just like list or tuple. Every element in
dictionary is mapped with key-value pair. The dictionary element can be referred to
a key with the associated value.
What is a dictionary?
Dictionaries are mutable, unordered collections with elements in the form of a
key:value pairs the associate keys to value. – Textbook Computer Science with
In the dictionary, a key is separated from values using colon (:) and the values with
commas.
Creating a Dictionary
To create a dictionary follow this syntax:
<dictionary-object> = {<key>:<value>,<key:value>,.....}
According to the syntax:
<dictionary-object>: It is just like a variable, referred as dictionary object
=: As usual, it is assignment operator
{}: The curly braces are used to write key-value pairs inside
48
key:value pair: The items or elements of dictionary object will be written in this
way
Points to remember:
While creating a dictionary always remember these points:
● Each value is separated by a colon
● The keys provided in the dictionary are unique
● The keys can be of any type such as integer, text, tuple with immutable
entries
● The values can be repeated
● The values also can be of any type
50
d = {1:'Virat Kohli',2:'Ajinkya Rehane',3:'Subhman Gill'}
#Priting with keys
print(d[1],d[3])
#Printing all values
print(d)
The process of taking a key and finding a value from the dictionary is known as
lookup. Moreover, you cannot a access any element without key. If you try to
access a value with key doesn’t exist in the dictionary, will raise an error.
Now have a look at the following code:
d=
{'Mines':'RajeshThakare','HR':'DineshLohana','TPP':'KamleshVerma','Scho
ol':'A. Vijayan','Hospital':'ShailendraYadav'}
for i in d:
print(i, ":",d[i])
In the above code you can see the variable i prints the key and d[i] prints the
associated value to the key.
d=
{'Mines':'RajeshThakare','HR':'DineshLohana','TPP':'KamleshVerma','Scho
ol':'A. Vijayan','Hospital':'ShailendraYadav'}
for i,j in d.items():
print(i, ":",j)
Here, I have separated the values using two variables in the loop.
You can also access the keys and values using d.keys() and d. values() respectively.
It will return the keys, and values in the form of sequence. Observe this code and
check the output yourself:
d=
{'Mines':'RajeshThakare','HR':'DineshLohana','TPP':'KamleshVerma','Scho
ol':'A. Vijayan','Hospital':'ShailendraYadav'}
print(d.keys())
51
print(d.values())
Create dictionary using dict() function
A dict() function can be used to create a dictionary and initialize the elements as
key:value pair. For example,
pr = dict(name='Ujjwal',age=32,salary=25000,city='Ahmedabad')
print(pr)
You can also specify the key:pair value in following manners:
pr = dict({'name':'Ujjwal','age':32,'salary':25000,'city':'Ahmedabad'})
print(pr)
You can also specify the key-values in the form sequences (nested list) as well.
Observe the following code:
pr =
dict([['name','Ujjwal'],['age',32],['salary',25000],['city','Ahmedabad']])
print(pr)
Add elements to a dictionary
You can add an element to the dictionary with the unique key which is not already
exist in the dictionary. Look at the following code:
pr =
dict([['name','Ujjwal'],['age',32],['salary',25000],['city','Ahmedabad']])
pr['dept']='school'
print(pr)
Update an element in a dictionary
To update the element, use a specific key and assign the new value for the
dictionary. Observe this code:
d = dict({'name':'Ujjwal','age':32,'salary':25000,'city':'Ahmedabad'})
d['salary']=30000
print(d)
52
Deleting element from the dictionary
You can delete the elements by using del, pop() and popitem() function. The pop()
function we will discuss in another article. Observe the following code for del:
d = dict({'name':'Shyam','age':32,'salary':25000,'city':'Ahmedabad'})
del d['age']
Membership Operator
As we you know in and not in operator we have used with list and tuple, similarly
used with dictionary. If key is present in the dictionary, it will return true otherwise
false. Look at the code:
d = dict({'name':'Shyam','age':32,'salary':25000,'city':'Ahmedabad'})
if 'name' in d:
print("Key found")
else:
print("Key not found")
if 'Shyam' in d.values():
print("Value found")
else:
print("Value not found")
SORTING TECHNICS:
Sorting means arranging the elements in a specified order i.e. either ascending or
descending order.
• Two sorting techniques are
(i) Bubble Sort – It compares two adjoining values and exchange them if they are
not in proper order.
(ii) Insertion Sort – suppose an array A with n elements A[1], A[2],…..A[N] is in
memory. The insertion sort algorithm
scans A from A[1] to A[N] inserting each element A[z] into its proper position in
the previously sorted
subarray A[1], A[2]…….A[x-1]
53
Bubble Sort
Simplest sorting algorithm. Iterates over the list, in each iteration it compares
elements in pairs and keeps swapping them such that the larger element is moved
towards the end of the list.
Example
Here we sort the following sequence using bubble sort
Sequence: 2, 23, 10, 1
First Iteration
(2, 23, 10, 1) –> (2, 23, 10, 1), Here the first 2 elements are compared and remain
the same because they are already in ascending order.
(2, 23, 10, 1) –> (2, 10, 23, 1), Here 2nd and 3rd elements are compared and
swapped(10 is less than 23) according to ascending order.
(2, 10, 23, 1) –> (2, 10, 1, 23), Here 3rd and 4th elements are compared and
swapped(1 is less than 23) according to ascending order
At the end of the first iteration, the largest element is at the rightmost position
which is sorted correctly.
Second Iteration
(2, 10, 1, 23) –> (2, 10, 1, 23), Here again, the first 2 elements are compared and
remain the same because they are already in ascending order.
(2, 10, 1, 23) –> (2, 1, 10, 23), Here 2nd and 3rd elements are compared and
swapped(1 is less than 10) in ascending order.
At the end of the second iteration, the second largest element is at the adjacent
position to the largest element.
Third Iteration
54
(2, 1, 10, 23) –> (1, 2, 10, 23), Here the first 2 elements are compared and swap
according to ascending order.
The remaining elements are already sorted in the first and second Iterations. After
the three iterations, the given array is sorted in ascending order. So the final result
is 1, 2, 10, 23.
Insertion Sort
In this algorithm, we segment the list into sorted and unsorted parts. Then we
iterate over the unsorted segment and insert the element from this segment into the
correct position in the sorted list.
Example
Here we sort the following sequence using the insertion sort
Sequence: 7, 2, 1, 6
(7, 2, 1, 6) –> (2, 7, 1, 6), In the first iteration, the first 2 elements are
compared, here 2 is less than 7 so insert 2 before 7.
(2, 7, 1, 6) –> (2, 1, 7, 6), In the second iteration the 2nd and 3rd elements are
compared, here 1 is less than 7 so insert 1 before 7.
(2, 1, 7, 6) –> (1, 2, 7, 6), After the second iteration (1, 7) elements are not in
ascending order so first these two elements are arranged. So, insert 1 before 2.
(1, 2, 7, 6) –> (1, 2, 6, 7), During this iteration the last 2 elements are compared
and swapped after all the previous elements are swapped.
**************************************************************
55