Unit 2 (Computational Thinking and Programming)
Unit 2 (Computational Thinking and Programming)
a) E b) F c) G d) D
Q2. ASCII is a _________ bit code and ISCII is a ___________ bit code.
a) 8, 7 b) 7, 8 c) 8, 8 d) 7, 7
Q3. According to the distributive law A (B+C) = __________.
a) ABC b) AB+AC c) A+B+C d) A+BC
Q4. Convert the following: (i)(4A)16=(______)2 (ii) (106)10=(_____)8
Q5. Convert the decimal number 106 to
a) binary and b) octal.
Q6. ASCII uses ____ bits to represent Characters.
a) 5 b) 6 c) 7 d) 8
Q7. How many bits forms a Kilo Byte?
a) 8194 Bits b) 8192 bits c) 4096 bits d) 1024 bits
Q8. Convert the following number in to given numbers:
a) (345.24)10 =( )2 b) (A35.57)16 =( )8
Q9. Convert the following numbers in the given equivalent number system.
a). (234.56)10 = ( )2 b) (1101111.11011)2 = ( )16
Q10. Full form of USB
a) Uniform Service Bus b) Universal Serial Bus c). Universal Sector Buffer d) Universal
Service Bus
Unit – 2 (Computational Thinking and Programming)
Problem and Problem Solving
In computer science, "problem" refers to a task or challenge that requires a solution. The process
of identifying a problem, developing an algorithm, and implementing an algorithm to develop a
computer program is called Problem Solving.
Steps required for solving a problem
● Analyzing the problem
● Developing an Algorithm
● Coding
● Testing and Debugging
21
START
Step 1 → Take an integer number A as
input Step 2 → Divide A by 2, and store the
remainder as r
Step 3 → If r is zero, Display 'Even'
Step 4 → Else Display 'Odd'
STOP
Coding
Coding is the process of creating computer programs.
Testing
Testing is a process to check if an application is working as expected. The main objective of
Testing is to find errors.
Debugging
Debugging is the activity to fix the errors found in the application during the testing phase.
Representation of Algorithms
There are two common methods of representing an algorithm —flowchart and pseudocode.
Pseudocode
● Pseudocode is a way of representing an algorithm in readable and easy language.
● Pseudocode is not an actual program. So, it cannot be executed.
● Some of the frequently used keywords while writing pseudocode are INPUT, COMPUTE, PRINT
IF/ELSE, START, STOP
Advantages of Pseudo-Code:
1. Easily convertible to a Programming Language
2. Easy to understand and read
Write a pseudocode for identifying if a number is even or odd.
INPUT number A
COMPUTE remainder as r = A%2
IF r ==0 PRINT 'Even'
ELSE PRINT 'Odd'
Decomposition
Decomposition is the process of breaking a complex computer problem into smaller parts that are
easily manageable and solvable
Computer Program:
22
A computer program is a set of instructions written in a programming language that can be
executed by the computer to perform and solve a certain task.
Python Programming Language:
Python is an interpreted, high-level programming language. It was developed by Guido van Rossum.
It is user-friendly and is most popular for its easy-to-use syntax and readable code. It is case
sensitive.
Working in Python
i) Install Python on the computer (https://www.python.org/downloads/).
ii) Use Python IDLE (Integrated Development and Learning Environment) for developing python
Programs.
Interactive Mode
In Interactive Mode, a python statement is executed in a command-line shell. It provides instant
feedback for each statement while keeping prior statements in memory.
Script Mode
In script mode, the instructions are saved in a file with a '.py' extension and executed from the
beginning of the file. This mode is suitable for creating and running large programs.
Character Set:
A character set is a collection of valid characters that can be recognized by a language. Python
Language recognises the following characters as valid:
23
Letters : A-Z, a-z
Digits : 0-9
Special Symbol : + / @ ! - = <> == etc.
Whitespaces : '\n', '\t' etc.
Tokens
Tokens are the smallest individual units of a program.
Keywords
Keywords are reserved words with special meaning (known to the interpreter). These can not be
used as identifiers in a program.
Example: for, while, else, if
Identifier
A variable, function, class, module, or other objects are identified by a name known as identifier.
Rules for naming an identifier:
1. First character of a variable can be an alphabet (A-Z or a-z) or an underscore(_).
2. Next characters of a variable can be an alphabet (A-Z or a-z), an underscore(_) or a digit.
3. Keywords cannot be used as variables.
4. First character cannot be a digit.
5. Special characters including white spaces are not allowed.
Literals:
Literals are data-items that have a fixed value of a certain data type, such as a number, string,
boolean, or None. They are also known as Constants.
Example :
String literals (Text) : 'Hello World'
Numeric literals (Numbers) : 3.14
Boolean literals (Truth Value) : True/False
None Literal : The None keyword is used to define a null value or absence of a value. None is
different from 0.
Relational Operators:
Relational operators perform comparison between values. An expression having relational operators
evaluates to either True or False. Example >, <, >=, <=, ==, !=
Logical Operators:
These operators are used to combine conditional statements.
Examples:
Examples:
○ = (Assign): Assigns the value on the right to the variable on the left.
○ +=, -=, *=, /=: These operators combine arithmetic operations with assignment.
Membership Operators:
Examples:
Identity Operators:
Examples:
○ is: True if the operands are identical (refer to the same object).
○ is not: True if the operands are not identical (do not refer to the same object).
Python Comments
Comments are descriptions about the code. They help other programmers understand the
functionality of the code. Comments are ignored by the Python interpreter.
Variable
25
Variables refer to an object (data items like int, float, list, dictionary etc.) stored in the memory. Value
stored in a variable can be changed during the program execution.
Rules for naming a variable are the same as the rules for naming an Identifier.
Data Type
Data type represents the type of data a Variable or a Literal is referring to. Each data type has specific
characteristics and operations associated with it. In Python, there are various data types, including
number, string, boolean, list, tuple, and dictionary.
Mutable Objects:
Mutable data objects are objects that can be changed after they are created. It is possible to add,
remove, or modify elements within these data types. Example of mutable data types: List, Set and
Dictionary.
Immutable Objects :
26
Objects whose values cannot be changed after they are created are called immutable objects. To
change the value, a new object is created. Example of immutable data types: Number (Integer, Float),
String, and Tuple.
Sequence: Sequence is an ordered collection of items or elements which includes several built-in
types as String, List, and Tuple. Values in the sequence are called elements/items. Each element in a
sequence has a unique index.
String:
● A string is an ordered sequence of characters enclosed in single/double/triple quotes.
● Single Line String : Terminates in a single line. Example – 'This is an example of single line'
● Multi Line String : Does not terminate in a single line. A multiline string may be created using
three quotes
List:
27
● List is an ordered sequence data type which can store values of any data type.
● List is mutable.
● List is enclosed in square brackets [ ]
● Example : [ ] is an empty List,
[5, 6.5, True, 'Hello'] is a List having 5, 6.5, True and 'Hello' as four elements.
Tuple:
● Tuple is an ordered sequence which can store values of any data type.
● They are immutable, i.e the items of a Tuple cannot be updated after creation.
● Tuple is enclosed in parenthesis ( )
● Example : t=( ) is an empty Tuple
t=(9,) is a Tuple with 9 as an item
t=(8, 5, 9.5, False) is a Tuple with 8, 5, 9.5, False as four items
Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping data
type in Python called dictionary.
Dictionary:
● Dictionary in Python stores items in the form of key-value pairs
● Syntax is dict_variable = {key1:value1, key2:value2, …, key-n:value-n}
● Items in a dictionary are enclosed in curly brackets { } and are separated by commas
● In a key-value pair, the key is separated from the value using a colon (:)
● To access any value in the dictionary, specify the key as the index using square brackets [ ].
● Example : { } is an empty dictionary,
D = {'name':'Python','version':'3.7.2', 'OS': 'Windows'}
print(D['version']) # shows 3.7.2 as output
Special Data-type: None
The None data type/keyword is used to indicate absence of a value (No value or Missing Value).
Example
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
Operator Precedence(PEMDAS)
PEMDAS stands for Parentheses, Exponents, Multiplication and Division, and Addition and
Subtraction. Let's look at each component:
28
Expression
An expression is combination of operators, operands, literals and parenthesis. An expression
produces a value when evaluated.
Evaluation of Expression
1. Evaluate the expression 50 + 20 * 30
Evaluation:
= 50 + (20 * 30) #precedence of * is more than that of +
= 50 + 600
= 650
2. Evaluate the expression 100 - 20 + 50
Evaluation:
The two operators (–) and (+) have equal precedence and the associativity is from left to right so the
left operator (i.e. -) will be evaluated first.
= (100 – 20) + 50
= 80 + 50
= 130
3. Evaluate the expression 9 + 3 ** 2 * 4 // 3
Evaluation:
= 9 + (3 ** 3) * 4 // 3
= 9 + 27 * 4 // 3 (* and // has left to right associativity)
= 9 + 108 // 3
= 9 + 36
= 45
Type conversion
It is the process of converting the value from one data type into another. Python supports two ways
of Type conversion:
● Implicit conversion
● Explicit conversion
Implicit conversion
This type of conversion is performed by Python Interpreter automatically without the user's
intervention.
Example:
num1 = 20 # num1 is integer
num2 = 30.5 # num2 is float
sum1 = num1 + num2 # sum1 will use float to avoid
# loss of fractional part during addition
29
print(sum1)
print(type(sum1))
Output:
50.5
<class 'float'>
Explicit Conversion:
This type of conversion is performed by the user manually. It is also known as type-casting. Explicit
type-casting is performed using functions such as int( ), float( ), str( ) etc.
Syntax : new_data_type (expression)
Example
num1 = input("Enter a number : ") # takes a string input by default
var1 = int(num1) #converts string to integer
var1 = var1 * 3
print(var)
Output
Enter a number : 2
6
Question 1:
Write the output of the given Python code :
a=0
a+ =2
print (a)
a) 2 b) 4 c) 6
Question 2:
Write the output of the given Python code :
a = 20
if a > = 22:
print(“if”)
elif a >= 21:
print(“elif”)
else:
print(“else”)
a) Else b) else c)elif
Question 3:
Which Operator is used for comparison of values?
a) Logical Operators b) Assignment Operators c) Relational Operators
Question 4:
What will be the output of the following code :
a=1
a, b = a+1, a+1
print(a)
print(b)
a) 2,2 b)4,2 c)2,6
Question 5:
30
Use IDLE to calculate : [CBSE Text Book]
(a) 6 + 4 * 10
(b) (6 + 4) * 10
i) (a) 46 b) 100 ii)a) 100 b)46 iii) a)100 b)100
Question 6:
What will be the output of the following code : [CBSE Text Book]
a = 3 – 4 + 10
b=5*6
c = 7.0/8.0
print(a,b,c, sep=”,”)
i)9,30,0 ii)9,30,1 iii)10,30,0
Question 7:
What will be the output of following code?
X, Y=2,6
X,Y = Y,X+2
print(X,Y)
a) 17 5 b)6 4 c)4 6
Question 8:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
a) True b)False c)True or False
Question 9:
x = ["apple", "banana"]
print("banana" in x)
a) True b)False c)True or False
Question 10:
What will be the output of following code?
12 & 13
a) 12 b)13 c)12 & 13
Question 11:
Which are correct arithmetical operations?
i) a = 1*2
ii) 2 = 1+1
iii) 5 + 6 = y
iv) Seven = 3 * 4
Question 12:
Which operations result in 8?
i) 65 // 8
ii) 17 % 9
iii) 2 * * 4
iv) 64 * * 0.5
Question 13:
If the value of a = 20 and b = 20, then a+=b will assign ________ to a
31
a) 40 b) 30 c) 20 d) 10
Question 14:
The ____________ operator is used to find out if division of two number yields any remainder
a) / b) + c) % d) //
Question 15:
Which of the following is the relational operator
a. //
b. =
c. ==
d. and
Errors
A programmer can make mistakes while writing a program, and hence, the program may not execute
or may generate wrong output. The process of identifying and removing such mistakes, also known
as bugs or errors, from a program is called debugging.
Errors occurring in programs can be categorised as:
i) Syntax errors.
ii) Logical errors
iii) Runtime errors
Syntax Error
Like other programming languages, Python has its own rules that determine its syntax. The
interpreter interprets the statements only if it is syntactically (as per the rules of Python) correct. If
any syntax error is present, the interpreter shows error message(s) and stops the execution there.
For example, parentheses must be in pairs, so the expression (10 + 12) is syntactically correct,
whereas (7 + 11 is not due to absence of right parenthesis. Such errors need to be removed before
the execution of the program
Some of the Common Syntax Errors are
● Parenthesis Mismatch
● Misspelled keyword
32
● Incorrect Indentation
Logical Error
Logical errors occur when the code runs without any errors, but the output is not as expected. Logical
errors are caused by a problem in the logic of the code.
Example : Average = mark_1 + mark_2 / 2 # incorrect calculation of average marks
Corrected Code : Average = (mark_1 + mark_2 ) / 2
Runtime Error
A runtime error causes abnormal termination of the program during the execution. Runtime error
occurs when the statement is correct syntactically, but the interpreter cannot execute it.
Runtime errors do not appear until after the program starts running or executing.
Example: 'division by zero'
num1 = 5.0
num2 = int(input("num2 = ")) #if the user inputs zero, a runtime error will occur
print(num1/num2)
Flow of Control
Flow of Control refers to the order in which statements are executed in a program.
Sequential Flow
The default control flow in a program is sequential flow, in which statements are executed line-by-
line one after the other in a sequence in which they are written.
Example
x=6
y=7
z=y-x
print(z)
Conditional Flow
Conditional flow refers to execution of certain statements only if a specific condition is met. This is
accomplished by the use of conditional statements such as if, if-else, and if-elif-else.
Example
num = int(input("Enter a number : "))
if(num>5):
print("Number is greater than 5")
else:
print("Number is less than 5")
Output
Enter a number : 55
Number is greater than 5
Iterative Flow
Iteration means 'repetition'.
Iterative flow repeats statements in a block of code. Repetition or looping can be performed a fixed
number of times or until a certain condition is met. This is accomplished through the use of iterative
statements: for and while.
Example-1
name = input("Enter your name : ")
for x in range(5): # range function creates a sequence of integers from 0 to 4
33
print("Hello", name)
Example-2
name = input("Enter your name : ")
i=1
while i<=5:
print("Hello", name)
i +=1
MCQ
34
Following is an algorithm for going to school or college. Can you suggest improvements in this to
include other options?
Reach_School_Algorithm
a) Wake up
b) Get ready
c) Take lunch box
d) Take bus
e) Get off the bus
f) Reach school or college
Short Answers
Answer the Following Questions (Short Answers)
1) What is empty statement in Python? What is its need?
2) Write a program to check a character is vowel or not
3) Explain the data types in python
4) Write short notes on types of operators in python with appropriate example
5) Write a program to check whether a years is leap year or not.
6) What is syntax error? Give one example.
7) What is the difference between ‘=’ and ‘==’? Explain with the help of an example.
8) What is the difference between mutable and immutable data types?
9) Differentiate between logical and runtime error?
10)What is the difference between the following operators?
a. * and **
b. = and ==
c. Logical error and runtime error
d. / and //
Long Answers
Answer the Following Questions (Long Answers)
1) What is the difference between a keyword and an identifier?
2) Classify the different types of decision-making statements.
3) Explain briefly constant, variables, expression, keywords and statements available in python.
4) What do you understand by precedence of operators? What is the precedence of arithmetic
operators?
5) What are the three types of flow of control in a program.
STRING
INTRODUCTION
It is a collection of characters (alphabets, digits or special characters including spaces) that is
enclosed in single quotes (‘ ’) or double quotes (‘‘ ’’) or triple quotes (‘‘‘ ’’’).
Ex- 'Hello Students’, "1412” etc.
Strings are immutable, means that the contents of the string cannot be changed after it is created.
INDEXING IN STRING
It is a process in which each character of string has its index or can be accessed using its index. The
first character in the string has index 0, the next has index 1, and so on. The index of the last
character will be the length of the string minus one (Forward indexing).
35
There is another way (Backward indexing) for indexing from last character (index = -1) to first
character (index = -length of the string)
STRING OPERATIONS
(1) Concatenation operator (+) – The Concatenation operator adds or concat two strings.
ex: -
>>>Str1= ‘Welcome’
>>>Str2 = ‘ to KVS’
>>>print(Str1+Str2)
’Welcome to KVS’
Concatenation operator works for string objects only. If we try another data type with string it
will produce error.
IN- Returns True if a character or a substring NOT IN- Returns True if a character or a
exists in the given string; otherwise, False. substring does not exist in the given string;
ex: - >>>‘N’ in ‘KVS’ otherwise, False
36
(4) String Slicing: - Extracting a subpart from a main string is called slicing. It is done by using a
range of indices.
Syntax - string_name[Start:Stop:Step]
Note: It will return a string from the index start to stop-1.
(5) Traversing: - Traversing means iterating through the elements of string, one character at a
time.
Example Output
>>>for a in Str: S*
print(a,’*’) t*
u*
d*
e*
n*
t*
s*
BUILT-IN FUNCTIONS/METHODS
Function/Met syntax Description
hod
len( ) len(str) Returns the length of the string
count( ) str.count(sub, start, end) It returns number of times substring str
occurs in the given string.
37
split( ) str.split(“,”) Breaks up a string at the specified separator
and returns a list of substrings
capitalize( ) str.capitalize( ) Converts the first letter of the string in
uppercase
title( ) str.title( ) It returns the string with first letter of every
word in the string in uppercase and rest in
lowercase.
find( ) str.find(sub, start, end) It is used to search the first occurrence of the
substring in the given string.
replace( ) str.replace(old, new) It replaces all the occurrences of the old string
with the new string.
index( ) index(substr, start, end) It also searches the first occurrence and
returns the lowest index of the substring.
lower( ) str.lower( ) It converts the string into lowercase
islower( ) str.islower( ) It returns True if all the letters in the string
are in lowercase otherwise false
upper( ) str.upper( ) It converts the string into uppercase
isupper( ) str.isupper( ) It returns True if all the letters in the string
are in uppercase otherwise false.
isalpha( ) str.isaplha( ) It checks for alphabets in an inputted string
and returns True in string contains only
letters else false.
isalnum( ) str.isanum( ) It returns True if all the characters are
alphanumeric else false.
isdigit( ) str.sidigit( ) It returns True if the string contains only
digits, otherwise false.
lstrip( ) str.istrip(chars) It returns the string after removing the space
str.istrip( ) from the left of the string
38
partition( ) str.partition(separator) It splits a given string into three parts based
on the first occurrence of a specified
separator. It returns a tuple containing the
three parts: the portion before the separator,
the separator itself, and the portion after the
separator.
join( ) separator.join(iterable) It is used to concatenate elements from an
iterable (like a list or tuple) into a single
string, with a specified separator between
each element.
endswith( ) string.endswith(substring, It returns True if the string ends with the
start, end) given substring, and False otherwise.
39
Multiple Choice Question
Q.1 What is the output of the following code?
example = "snow world"
example[3] = 's'
print (example)
(a) snow (b) snow world (c) Error (d) snos world
Q.2 Which of the following statement will return the last three characters of a string ‘str’?
(a) str[3: ] (b) str[ : 3] (c) str[-3: ] (d) str[ : -3]
Q.3 Find the operator which cannot be used with a string in Python from the following:
(a) + (b) not in (c) * (d) //
Q.4 Which of the following operations on a string will generate an error?
(a) "PYTHON"*3 (b) "PYTHON" + "20" (c)"PYTHON" + 10 (d) "PYTHON" + “LANGUAGE"
Q.5 Which of the following is not a valid string in Python?
(a) “Hello” (b) ‘Hello’ (c) “Hello’ (d) None of the above
Q.6 Which of the following operators is used for concatenation of two strings?
(a) - (b) * (c) + (d) /
Q.7 Which of the following functions will return the total number of characters in a string?
(a) count( ) (b) index( ) (c) len( ) (d) all of these
Q.8 Which of the following function is used for checking whether a string is containing digits only:
(a) isalpha( ) (b) isdigit( ) (c) isalnum( ) (d) None of the above
40
Q.9 What will be the output of above Python code?
str1= “6/4”
print(“str1”)
(a) 1 (b) 6/4 (c) str1 (d) 1.5
Q.10 Which of the following will result in an error?
str1="python"
(a) print(str1[2]) (b) str1[1]="x" (c) print(str1[0:9]) (d) None of these
42
Short Questions
Q.1 Write a python code to give this output :
H # Ans. s='HELLO'
E # for x in s:
L # print(x,'#')
L #
0 #
# Ans. N=5
## for I in range(1,N+1):
### print(“#”*I)
####
#####
Q.4 Which functions would you chose to use to remove leading and trailing white spaces from a
given string?
Ans. Python String strip( ) function will remove leading and trailing white spaces. If you want to
remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
Q.5 Find the value stored in C at the end of this code snippet:
str="Darjeeling Tea has a strong flavour"
C=0
for i in str:
if i in 'aeiouAEIOU':
C += 1
print(C)
Ans. 12
Q.6 (A) Assertion: str1=”Hello” and str2=”World” then print(str1*3) will give error
(R) Reason : * replicates the string hence correct output will be HelloHelloHello
Ans. A is false and R is correct.
Q.7 Using string replication techniques print the following pattern using any loop.
Hello
43
Hello Hello
Hello Hello Hello
Ans. for a in range(1,4):
print("hello " * a)
Q.8 What is the difference between partition( ) and split( ) function in Python ?
Ans. partition( ) – it partitions the string on the first occurrence of substring.
ex:- s='hello all'
s.partition('a') => ('hello ', 'a', 'll')
s.partition(‘all’) => ('hello ', 'all', ‘ ‘)
split( ) – it returns a list of strings as splitted. ex:- s='hello all'
s.split( ) => [‘hello’, ‘all’ ]
Q.9 What is the concatenation operator in Python ?
Ans. Concatenation operator ( +) –The concatenation operator adds or concat two strings. ex:-
s1=‘Welcome’
s2 = ‘All’
print(s1+s2)
=>Output :- WelcomeAll
Q.10 Write a program to change a given string to a new string exchanging first and last character
Ans. s=input(“Enter any string”)
ns = s[-1:] + s[1:-1] + s[:1]
print (“New String- ”,ns )
Long Question
Q.1 Write a program to calculate digits and letters in a string.
Ans string=input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
elif(i.isalpha()):
count2=count2+1
print("The number of digits is:",count1)
print("The number of characters is:",count2)
Q.2 Write a program to count a specific character in a string.
Ans. string=input("Enter string:")
count=0
ch=input("Enter character you want to count-- ")
count=string.count(ch)
print("The count of ",ch,"in string is ",count)
Q.3 Consider the following string country:
country= "Great India"
What will be the output of the following string operations(Any Four):-
44
(a) print(country[0:len(country)]) Ans. (a)Great India
(b) print(country[-7:-1]) (b)t Indi
(c) print(country[::2]) (c)GetIda
(d) print(country[len(country)-1]) (d)a
(e) print(2*country) (e)Great IndiaGreat India
(f) print(country[:3] + country[3:]) (f)Great India
Q.4 Find Output:
my_string = 'Jhunjhunu' Ans. Jhu
print(my_string[:3]) J@H@U@N@J@H@U@N@U@
for i in range(len(my_string)): Jhunjhunu
print(my_string[i].upper(),end="@") Njh
print()
print (my_string)
print (my_string[3:6])
Q.5 Write a Python Program to input a string to check whether it is a Palindrome string or not. (A
Palindrome string is that which is same from both ends like – NITIN, MALAYALAM, PULLUP)
Ans. s=input("Enter a word :")
print ("You entered :", s)
length=len(s)
rev=""
for i in range (-1,-length-1,-1):
rev=rev+s[i]
if s==rev:
print ("Yes, palindrome")
else:
print ("Not a palindrome")
Case Study based question
Q.1 Ravee is developing a program to greet users based on their input. It takes a name as input
and returns a greeting message in the format "Hello, [name]!".
Ans. user_name = input("Enter your name: ")
print(“Hello”,user_name,”!”)
Q.2 Gorank is tasked with processing a file name and extracting the file extension. Program takes
a file name as input and return the output of its extension.
Ans. file_name = input("enter the file name with extension: ")
if '.' in file_name:
print("The file extension of", file_name, "is", file_name.split('.')[-1])
else:
print("No extension found")
45
LIST
INTRODUCTION
Lists are used to store multiple items in a single variable. Lists are enclosed in square brackets and
the elements of the list are separated by commas. List is a mutable data type, means that the contents
of the list can be changed after it is created.
ex: - L = [12, 23, ‘A’, “45”]
L1 = [ ] # L1 is a blank list
L2 = list( ) # list( ) function is used to create list L2
L3 = [1,2,3,4,5] # L3 is an integer list
L4 = ["ABC", 15, False, 25.5, "male"] # L4 is a list with mix data types
L5 = [‘a’, [2,4,’b’], 56] # L5 is a nested list
INDEXING IN LIST
It is a process in which each element of a list has its index or can be accessed using its index. The first
element of the list has index 0, the next has index 1, and so on. The index of the last element will be
the length of the minus one (Forward indexing).
There is another way (Backward indexing) for indexing from last element (index = -1) to first
element (index = -length of the list)
LIST OPERATIONS
(1) Concatenation (+ Operator): Python allows us to join two or more lists using + operator.
ex: - >>> l1 = [1,3,5,7,9]
>>> l2 = [2,4,6,8,10]
>>> l3 = [‘abc’, “qwe”]
>>>l1 + l2 + l3 # + operator
[1,3,5,7,9,2,4,6,8,10, ‘abc’, “qwe”]
(2) Repetition/ Replication Operator (* operator): Python allows us to replicate a list using
repetition operator depicted by symbol ‘*’.
ex: - >>> str1 = ['Help']
>>> str1 * 4
[' Help ', ' Help ', ' Help’, '' Help’']
(3) Membership (IN/ NOT IN operator) :
Like strings, the membership operators IN checks, if NOT IN operator returns True if the
the element is present in the list then returns True, element is not present in the list, else it
46
else returns False. returns False.
ex: - >>>‘N’ in [‘K’, ‘V’, ‘S’ ] ex: - >>>‘N’ not in [‘K’, ‘V’, ‘S’ ]
False True
>>>‘V’ in [‘K’, ‘V’, ‘S’ ] >>>‘V’ not in [‘K’, ‘V’, ‘S’ ]
True False
List Slicing: - Like strings, the slicing operation can also be applied to lists. List elements can be
accessed in subparts.
Syntax- list_name[start:stop:step]
L = [2,7,9,10,13,15,17,19,23,25]
Slice Generates
L[4: ] [13, 15, 17, 19, 23, 25]
L[ : 3] [2,7,9]
L[2: 5] [9,10, 13]
L[4: : 2] [13, 17, 23]
L[2 : 7 : 2] [9, 13, 17]
L[ : : -1] [25, 23, 19, 17, 15, 13, 10, 9, 7, 2]
L[ : : -2] [25, 19, 15, 10, 7]
L[6 : 1: -2] [17, 13, 9]
L[-8 : 8 ] [9, 10, 13, 15, 17, 19]
L[3 : -2 : 2] [10, 15, 19]
L[6 : -9 : -2] [17, 13, 9]
(4) Traversing: - Traversing means iterating through the elements of a list, one element at a time.
ex: - >>>L1 = [1,2,3,4] 1
>>>for a in L1: 2
print(a) 3
4
(5) Modifying a List element/Mutability of a List: - The elements of a list can be modified by using
L[index]=new_value. Since a list can be modified in place, i.e. the existing list object is not
destroyed and recreated.
(6) List Comparisons: - The relational operators >, >=, <, <=, ==, != can be applied for comparison
between two lists results will come in True or False. The following rules are observed:
47
(a) For equality (==) operator: - Equality evaluates to True only when all the elements of one
list match all the elements of the other list and both the list have the same number of
elements.
(b) For all other operators - The elements are compared sequentially using the operator
under consideration.
(c) If two lists are of different lengths and if one of the list has an element at an index
position and the other list does not have an element at that position then the evaluation
proceeds as follows:
• something/somevalue > empty/nothing evaluates to True
• something/somevalue < empty/nothing evaluates to False
List Functions :-
Function Syntax Description
list( ) list(sequence) It returns a list created from the passed
arguments, which should be a sequence type
(string, list, tuple etc.). if no argument is passed, it
will create an empty list.
append( ) list.append(items) It adds a single item to the end of the list.
extend( ) list1.extend(list2) It adds one list at the end of another list.
insert( ) list.insert(index_no, value) It adds an element at a specified index
reverse( ) list.reverse( ) It reverses the order of the elements in a list.
index( ) list.index(item) It returns the index of first matched item from the
list.
len( ) len(list) Returns the length of the list i.e. number of
elements in a list
sort( ) list.sort( ) This function sorts the items of the list.
clear( ) list.clear( ) It removes all the elements from the list.
count( ) list.count(element) It counts how many times an element has
occurred in a list and returns it.
sorted( ) sorted(sequence,reverse= It returns a newly created sorted list; it does not
False) change in the original list.
pop( ) list.pop(index) It removes the element from the specified index
and also returns the element which was removed.
remove( ) list.remove(value) It is used when we know the element to be
deleted, not the index of the element.
48
max( ) max(list) Returns the element with the maximum value
from the list.
min( ) min(list) Returns the element with the minimum value
from the list
sum( ) sum(list) It returns the sum of elements of the list.
max( ) max(list) Returns the element with the maximum value
from the list.
min( ) min(list) Returns the element with the minimum value
from the list
sum( ) sum(list) It returns the sum of elements of the list.
MIND MAP OF LIST
>>>l.pop() >>>l.remove(20)
20
51
Ans. The similarity between Lists and Strings in Python is that both are sequences. The differences
between them are that firstly, Lists are mutable but Strings are immutable. Secondly, elements
of a list can be of different types whereas a String only contains characters that are all of
String type.
Q.6 Write a program to accept a list of numbers and find the sum of all the numbers in the list.
Q.7 WAP to search for an element in a given list of numbers.
Q.8 WAP to find the minimum element from a list of elements along with its index in the list.
Q.9 What will be the output of the following program:
l=[10,20,30,40,50,60]
for i in range(len(l)):
if(i%2==0):
print(l[i],end='#')
else:
print(l[i],end='@')
Q.10 What will be the output of following program:
odd = [1, 9]
odd.insert(1,3)
print(odd)
odd[2:2] = [5, 7]
print(odd)
Long Question
Q.1 Write a program that takes any two lists L and M of the same size and adds their elements
together to form a new list N whose elements are sums of the corresponding elements in L and M. For
instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4,6,13].
Q.2 Write a Python program to input 10 numbers to store in the list and print the third largest
number. For example, if the entered numbers in the list are List are 36, 25, 14, - 951, 75, - 85,
654, 88, 9521, 657, then output will be The third largest number is : 654
Q.3 Take a list of 10 elements. Split it into middle and store the elements in two different lists.
E.g.- INITIAL list : 5 10 6 12 3 25 66 44 1 90 After splitting : 5 10 6 12 3
25 66 44 1 90
Q.4 Find and write the output of the following Python code :
52
print(x[0]==8) False
print(len(x)) 4
x.extend([12,32,4])
print(len(x)) 7
Q.5 Consider the following list L=[13,18,20,10,18,23] Write python statements to perform
(a) Count number of times the value 18 is repeating
(b) Arrange values in descending order
(c) Remove the last element
(d) Insert 15 at index position 3
Q.6 Guddu is building a program to process student average marks. It takes marks of five subjects
and calculates the average marks.
Ans. student_marks = eval(input(" Enter marks of five subject in a list (Max. is 100): "))
total_marks=sum(student_marks)
avg_marks= total_marks/5
print("Average marks is: ", avg_marks)
53
TUPLE
INTRODUCTION
A tuple is a collection which is ordered and immutable (We cannot change elements of a tuple in
place). Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by
commas. Tuples can store a sequence of values belonging to any type. Tuples allows duplicate
members.
Ex:- T1 = ( ) # Empty Tuple
T2 = (4,5,6) # Tuple of integers
T3 = (1.5,4,9) # Tuple of numbers
T4 = (‘x’, ‘y’, ‘z’) # Tuple of characters
T5 = (‘a’,1.5,’KVS’,45) # Tuple of mixed values
T6 = (‘KVS’, ‘NVS’, ‘EMRS’) # Tuple of strings
>>>t2 = (10,) # Single element tuple
Note:- comma is necessary in single value tuples. Without a comma it will be a value, not a tuple.
>>>t3=(10,20,30,40,50) # Long tuple
>>>t4=(6,(4,5),9,7) # Nested Tuple
● tuple( ) function is used to create a tuple from other sequences.
● Indexing of tuple is similar to indexing of list.
● Difference between List and Tuple
S. No. List Tuple
01 Elements are enclosed in square brackets Elements are enclosed in parenthesis
i.e. [ ] i.e. ( )
02 It is mutable data type It is immutable data type
03 Iterating through a list is slower as Iterating through a tuple is faster as
compared to tuple compared to list
TRAVERSING A TUPLE
Traversing a tuple means accessing and processing each element of it. A tuple can be traversed using
a loop.
Ex:- >>> T1=(2,4,6,8,10) Output: 2
>>> for a in T1: 4
print(a) 6
8
10
ACCESSING TUPLES
Elements of a tuple can be accessed using Indexing and Slicing, same as in string and list.
if T1= (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’):
54
Elements C 0 M P U T E R
+ index Value 0 1 2 3 4 5 6 7
- Index Value -8 -7 -6 -5 -4 -3 -2 -1
OPERATORS IN TUPLE
Operation Name Description Example
Concatenation (+) Joining of two or more tuples is >>>t1 = (1, 2, 3)
called concatenation >>>t2 = (8, 9, 11)
Python allows us to join tuples >>>t1+t2
using concatenation operator (+) OUTPUT :
(1, 2, 3, 8, 9, 11)
(#concatenates two tuples)
>>>t1 = (1, 2, 3)
>>>t2 = (8, 9, 11)
>>>t3 = t1+t2
(#Created new tuple)
OUTPUT :
(1, 2, 3, 8, 9, 11)
Concatenation operator can also
be used for extending an
existing tuple.
>>>t1 = (1, 2, 3)
>>>t1 = t1 + (7,8,9)
>>>t1
It is used to repeat elements of a
>>>h1 = (‘H’ , ‘M’) >>>h1 * 3 (‘H’
Repetition (*) tuple. Repetition operation is
, ‘M’, ‘H’ , ‘M’, ‘H’ , ‘M’)
denoted by Symbol (*)
Membership The ‘in’ operator checks the >>>h1 = (‘H’ , ‘M’)
presence of element in tuple. If >>>’H’ in h1
the element is present it returns True
True, else it returns False. >>>’m’ not in h1
55
The not in operator returns True True
if the element is not present in
the tuple, else it returns False.
Slicing It is used to extract one or more >>>t1 = (1, 2, 3, 7, 8, 9)
elements from the tuple. Like >>>t1[2:4]
string and list, slicing can be (3, 7)
applied to tuples also. >>>t1 =(10, 20, 30, 40, 50,
60, 70, 80)
>>>t1[2 : 7]
(30, 40, 50, 60, 70)
>>>t1[ : 5]
(10, 20, 30, 40, 50)
>>>t1[: : -1]
(80, 70, 60, 50, 40, 30, 20, 10)
56
>>>t1 = tuple(range(7))
>>>t1
(0, 1, 2, 3, 4, 5, 6)
>>>t1=tuple(“tuples in python”)
This function returns the frequency
count( ) >>>t1.count(‘p’)
of an element in the tuple.
2
>>>t1=tuple(“tuples in python”)
>>>t1.index(‘n’)
This function returns the index of the 8
index( ) first occurrence of the element in the
given tuple. >>>t1=tuple(“tuples in python”)
>>>t1.index(‘f’)
ValueError: tuple.index(x): x not in tuple
>>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
This element takes tuple as an >>>sorted(t1)
argument and returns a sorted list.
sorted( ) [‘e’, ‘l’, ‘p’, ‘s’, ‘t’, ‘u’]
This function does not make any
change in the original tuple. >>>t1
(‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>t1 = (3, 8, 4, 10, 1)
>>>min(t1)
This function returns the minimum or 1
min( )
smallest element of the tuple. >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>min(t1)
‘e’
>>>t1 = (3, 8, 4, 10, 1)
>>>max(t1)
This function returns the maximum 10
max( )
or largest element of the tuple. >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>max(t1)
‘u’
>>>t1 = (3, 8, 4, 10, 1)
This function returns the sum of the
sum( ) >>>sum(t1)
elements of the tuple.
26
57
MIND MAP OF TUPLE
ANSWERS OF MCQ
(1) b, (2) c, (3) c, (4) c, (5) a, (6) d, (7) a, (8) d, (9) c, (10) a
Competency Based Question
Q.1 Discuss the utility and significance of Tuples, briefly.
Ans. It is a type of array. It plays a very important role in python. In python it is an immutable type
of container which stores any kind of data types. It is short in memory size in comparison to
lists.
Q.2 Lists and Tuples are ordered. Explain.
Ans. Lists and Tuples are ordered sequences as each element has a fixed position.
Q.3 Write the output of the following.
a=(23,34,65,20,5)
print(a[0]+a.index(5))
Ans. 27
Q.4 Create a tuple names as given here:
names = ('JAI', 'RAM', 'MAMTA', 'KAPIL', 'DINESH', 'ROHIT') Write proper code for getting:
('MAMTA', 'KAPIL', 'DINESH')
Ans. print(names [2 : 5 ])
Q.5 T1=(1,2) & T2=(“KV”,)
print(T2*2)
Ans. (‘KV’,’KV’)
Q.6 T1=(45,67,98)
T1=T1+(1,2,3)
print(T1)
Ans. (45,67,98,1,2,3)
Q.7 Consider the following tuple and write the code in python for the following statements:
T1=(12,3,45,’Hockey’,’Anil’,(‘a’,’b’))
(a) Display the first element of ‘T1’ (b) Display the last element of ‘T1’
(c) Display ‘T1’ in reverse order. (d) Display ‘Anil’ from tuple ‘T1’
(e) Display ‘b’ from tuple
59
Ans. (a) print(T1[0]) (b) print(T1[-1]) (c) print(T1[ : :-1]) (d) print(T1[4])
(e) print(T1[5][1])
Q.8 What is unpacking Tuple?
Ans. It allows a tuple of variables on the left side of the assignment operator to be assigned
respective values from a tuple on the right side. The number of variables on the left should be
the same as the number of elements in the tuple.
Q.9 What are nested tuples?
Ans A tuple containing another tuple in it as a member is called a nested tuple, e.g., the tuple
shown below is a nested tuple:
Employees = (4580,'Rahul', (82,67,75,89,90)) # nested tuple
Q.10 for i in tuple(“KVS”):
print(i+i)
Ans. KK
VV
SS
Very short Questions
Q.1 T1=(“Hockey”, “Cricket”, ‘Football’)
print(max(T1))
print(min(T1))
Ans. Hockey
Cricket
Q.2 What will be the output of the following Python Code?
tp = (5,)
tp1 = tp * 2
print(len(tp1))
Ans. 2
Q.3 Type Error occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
Ans. Because tuple1 is an integer not a tuple. So, we cannot find the length of the integer. If you
want to make tuple then you should write ( 5, )
Q.4 How to create an empty tuple? Also create a single element tuple.
Ans. t=( ) or t=tuple( ) single element tuple: t=(10,)
Q.5 Write a program that inputs two tuples and creates a third, that contains all elements of the
first followed by all elements of the second.
60
Ans. tup1 = eval(input("Enter First tuple :-"))
tup2 = eval(input("Enter second tuple :-"))
tup3 = tup1 + tup2
print(tup3)
Q.6 T1=('A',['B','D'],'C')
T1[1][1]='C'
print(T1)
Ans. ('A', ['B', 'C'], 'C')
Q.7 What is the difference between a List and a Tuple?
Ans.
List Tuple
Elements are enclosed in square brackets i.e. [ ] Elements are enclosed in parenthesis i.e. ( )
It is mutable data type It is immutable data type
Iterating through a list is slower as compared Iterating through a tuple is faster as
to tuple compared to list
61
n = int(input("Enter a number :- "))
tup += (n,)
ch = input("To quit enter y/Y =")
if ch == "y" or ch=="Y":
print(tup)
print("Max :-",max( tup ))
print("Min :-",min( tup ))
break
Q.2 Write a program to count vowels in a tuple?
Ans. T = tuple(input("Enter Name :"))
print(T)
v=0
for ch in T:
if ch in ['a','e','i','o','u']:
v=v+1
print("No. of vowels : ",v)
Q.3 What will be stored in variables a, b, c, d, e, f, g, h after following statements?
62