This page contains the CBSE Computer Science with Python class 11 Unit-4 chapter 2 Lists. You can find the solutions for chapter 2 of CBSE class 11 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 11 Computer Science with Python related topic Lists questions and answers for the Exercise.
Question 1
1. Define list
Answer 1
A list is a data structure used to store a collection of values in a single variable. The elements of a list are written inside square brackets
[ ] and are separated by commas. A list can store values of the same type or of different types, and since a list is mutable, its elements can be changed after creation.Example:
L = [10, 20, 30]
Question 2
2. What is the output of the following code:
a)
print type ([1,2])(i)
<type "complex">(ii)
<type "int">(iii)
<type "list"> ✔b)
a= [1, 2, 3, None, ( ), [ ]}print len(a)(i)
Syntax error ✔(ii)
4(iii)
5(iv)
6(v)
7Answer 2
a)
print type([1,2])The value
[1,2] is a list, so its type is:Answer:(iii)
<type 'list'>b)
a = [1, 2, 3, None, (), []}
print len(a)
This code contains a syntax error because the list starts with
[ but ends with }. The brackets do not match.Answer:(i) Syntax error
Question 3
3. Write the output from the following code:
A=[2,4,6,8,10]L=len(L)S=0for I in range(1,L,2):S+=A[I]print “Sum=”,SAnswer 3
The given code is:
# Given code from question
A = [2,4,6,8,10]
L = len(L)
S = 0
for I in range(1,L,2):
S += A[I]
print "Sum=", S
The given code has an error in the line:
L = len(L)
Here,
L has not been defined yet. The intended statement is clearly:L = len(A)
If corrected, then:
•
A = [2, 4, 6, 8, 10]•
L = 5•
range(1, 5, 2) gives 1, 3•
A[1] = 4•
A[3] = 8So:
•
S = 4 + 8 = 12Output (after correcting the obvious error):
Sum= 12
The logic of the program is to add the elements at the odd index positions.
Question 4
4. Find the errors from the following program
n=input (Enter total number of elements)l=range(n)print lfor i in (n);l[i]=input("enter element")print "All elements in the list on the output screen"for i on range(n):print l[i]Answer 4
Given program:
# Given program with errors
n = input (Enter total number of elements)
l = range(n)
print l
for i in (n);
l[i] = input("enter element")
print "All elements in the list on the output screen"
for i on range(n):
print l[i]
Errors and corrections
1.
The input prompt must be inside quotation marks:
n = input("Enter total number of elements")
2.
for i in (n); is incorrect:•
n is not iterable here•
; should be replaced by :Correct form:
for i in range(n):
3.
for i on range(n): is incorrect. on should be in.Correct form:
for i in range(n):
4.
Proper indentation is required for the loop body.
Corrected program
# Corrected program
n = input("Enter total number of elements")
l = range(n)
print l
for i in range(n):
l[i] = input("Enter element: ")
print "All elements in the list on the output screen"
for i in range(n):
print l[i]
This corrected program creates a list of size
n, takes input for each element, and then prints all elements.Question 5
5. Write a function group of list (list, size) that takes a list and splits into smaller list of given size.
Answer 5
This function divides the original list into smaller sublists, each containing the given number of elements.
# Function to split a list into smaller groups
def group_of_list(lst, size):
result = []
i = 0
while i < len(lst):
result.append(lst[i:i+size])
i = i + size
return result
Example
print group_of_list([1, 2, 3, 4, 5, 6, 7], 3)
Output
[[1, 2, 3], [4, 5, 6], [7]]
Thus, the list is broken into smaller parts of the required size.
Question 6
6. Write a function to find all duplicates in the list.
Answer 6
A duplicate means a value that appears more than once in the list.
# Function to find duplicate elements
def find_duplicates(lst):
duplicates = []
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] == lst[j] and lst[i] not in duplicates:
duplicates.append(lst[i])
return duplicates
Example
print find_duplicates([1, 2, 3, 2, 4, 5, 1, 6])
Output
[1, 2]
This function checks all pairs of elements and collects only the repeated values.
Question 7
7. For each of the expression below, specify its type and value. If it generates error, write error.
Assume that expressions are evaluated in order.
x= [1, 2, [3, 'abc', 4], 'Hi'](i)
x[0](ii)
x[2](iii)
x[-1](iv)
x[0:1](v)
2 in x(vi)
x[0]=8Answer 7
Given:
x = [1, 2, [3, 'abc', 4], 'Hi']
(i)
x[0]•
Value:
1•
Type:
int(ii)
x[2]•
Value:
[3, 'abc', 4]•
Type:
list(iii)
x[-1]•
Value:
'Hi'•
Type:
str(iv)
x[0:1]•
Value:
[1]•
Type:
list(v)
2 in x•
Value:
True•
Type:
boolBecause
2 is present as an element in the list.(vi)
x[0] = 8This is an assignment statement, not a value-returning expression.
•
Result: No printed value
•
Effect: the list becomes:
[8, 2, [3, 'abc', 4], 'Hi']
Since lists are mutable, changing an element by index is allowed.
Question 8
8. For each of the expression below, specify its type and value. If it generates error, write error:
List A= [1, 4, 3, 0]List B= ["x", "z", "t", "q"](i)
List A.sort ( )(ii)
List A(iii)
List A.insert (0, 100)(iv)
List A.remove (3)(v)
List A.append (7)(vi)
List A+List B(vii)
List B.pop ( )(viii)
List A.extend ([4, 1, 6, 3])Answer 8
Given:
# Initial lists for evaluation
ListA = [1, 4, 3, 0]
ListB = ['x', 'z', 't', 'q']
These expressions are evaluated in order.
(i)
ListA.sort()•
Type:
NoneType•
Value:
Nonesort() changes the list in place.After this step:
ListA = [0, 1, 3, 4]
(ii)
ListA•
Type:
list•
Value:
[0, 1, 3, 4](iii)
ListA.insert(0, 100)•
Type:
NoneType•
Value:
NoneAfter this step:
ListA = [100, 0, 1, 3, 4]
(iv)
ListA.remove(3)•
Type:
NoneType•
Value:
NoneAfter this step:
ListA = [100, 0, 1, 4]
(v)
ListA.append(7)•
Type:
NoneType•
Value:
NoneAfter this step:
ListA = [100, 0, 1, 4, 7]
(vi)
ListA + ListB•
Type:
list•
Value:
[100, 0, 1, 4, 7, 'x', 'z', 't', 'q'](vii)
ListB.pop()•
Type:
str•
Value:
'q'After this step:
ListB = ['x', 'z', 't']
(viii)
ListA.extend([4, 1, 6, 3])•
Type:
NoneType•
Value:
NoneAfter this step:
ListA = [100, 0, 1, 4, 7, 4, 1, 6, 3]
These examples show that many list methods modify the original list and return
None.Lab Exercise
Question 1 (Lab)
1. We can use list to represent polynomial.
For Example
p (x) = -13.39 + 17.5 x + 3 x2 + x4can be stored as
[-13.39, 17.5, 3, 1.0]Here ‘index’ is used to represent power of ‘x’ and value at the index used to represent the coefficient of the term.
Write a function to evaluate the polynomial for a given ‘x’.
Answer 1 (Lab)
If the list stores coefficients so that the index represents the power of
x, then the polynomial value can be found by:•
multiplying each coefficient by the corresponding power of
x•
adding all the terms
# Function to evaluate a polynomial
def evaluate_poly(coeffs, x):
total = 0
i = 0
while i < len(coeffs):
total = total + coeffs[i] * (x ** i)
i = i + 1
return total
Example
# Example: evaluate at x = 2
p = [-13.39, 17.5, 3, 0, 1.0]
print evaluate_poly(p, 2)
This evaluates the polynomial at
x = 2.Question 2 (Lab)
2. Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the its element is the sum of the first i+1 elements from the original list. For example, the cumulative sum of
[1, 2, 3] is [1, 3, 6].Answer 2 (Lab)
The cumulative sum means:
•
first element stays the same
•
second element becomes sum of first two
•
third becomes sum of first three, and so on
# Function to return cumulative sum
def cumulative_sum(lst):
result = []
total = 0
for item in lst:
total = total + item
result.append(total)
return result
Example
print cumulative_sum([1, 2, 3])
Output
[1, 3, 6]
Question 3 (Lab)
3. Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None. Then write a function called middle that takes a list and returns a new list that contains all but the first and last elements.
Answer 3 (Lab)
chop() removes the first and last element from the same list and returns None. middle() returns a new list without the first and last elements.# Function to modify the same list
def chop(lst):
del lst[0]
del lst[-1]
return None
# Function to return a new list
def middle(lst):
return lst[1:-1]
Example
# Example usage
a = [1, 2, 3, 4]
print middle(a)
chop(a)
print a
Question 4 (Lab)
4. Write a function called
is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise. You can assume (as a precondition) that the elements of the list can be compared with the relational operators <, >, etc.For example,
is_sorted ([1, 2, 2]) should return True and is_sorted ([‘b’, ‘a’]) should return False.Answer 4 (Lab)
This function returns
True if the list is in ascending order, otherwise False.# Function to check ascending order
def is_sorted(lst):
i = 0
while i < len(lst) - 1:
if lst[i] > lst[i + 1]:
return False
i = i + 1
return True
Example
# Example usage
print is_sorted([1, 2, 2])
print is_sorted(['b', 'a'])
Output
True
False
Question 5 (Lab)
5. Write a function called
remove_duplicates that takes a list and returns a new list with only the unique elements from the original. Hint: they don”t have to be in the same order.Answer 5 (Lab)
This function returns a new list containing only unique elements.
# Function to remove duplicates
def remove_duplicates(lst):
result = []
for item in lst:
if item not in result:
result.append(item)
return result
Example
print remove_duplicates([1, 2, 1, 3, 2, 4])
Output
[1, 2, 3, 4]
Question 6 (Lab)
6. Write a function that takes in two sorted lists and merges them. The lists may not be of same length and one or both may be empty. Don”t use any Python built -in methods or functions.
Answer 6 (Lab)
This function combines two already sorted lists into one sorted list.
# Function to merge two sorted lists
def merge_sorted(a, b):
result = []
na = 0
nb = 0
for x in a:
na = na + 1
for y in b:
nb = nb + 1
i = 0
j = 0
while i < na and j < nb:
if a[i] <= b[j]:
result = result + [a[i]]
i = i + 1
else:
result = result + [b[j]]
j = j + 1
while i < na:
result = result + [a[i]]
i = i + 1
while j < nb:
result = result + [b[j]]
j = j + 1
return result
Example
print merge_sorted([1, 3, 5], [2, 4, 6, 8])
Output
[1, 2, 3, 4, 5, 6, 8]
Question 7 (Lab)
7. Create a list that contains the names of 5 students of your class. (Do not ask for input to do so)
(i)
Print the list
(ii)
Ask the user to input one name and append it to the list
(iii)
Print the list
(iv)
Ask user to input a number. Print the name that has the number as inde x (Generate error message if the number provided is more than last index value).
(v)
Add “Kamal” and “Sanjana” at the beginning of the list by using “+”.
(vi)
Print the list
(vii)
Ask the user to type a name. Check whether that name is in the list. If exist, delete the name, otherwise append it at the end of the list.
(viii)
Create a copy of the list in reverse order
(ix)
Print the original list and the reversed list.
(x)
Remove the last element of the list.
Answer 7 (Lab)
A simple complete program is:
# Program on student names list
students = ["Ravi", "Meena", "Arjun", "Neha", "Pooja"]
# (i)
print students
# (ii)
name = raw_input("Enter one name to append: ")
students.append(name)
# (iii)
print students
# (iv)
index = input("Enter an index number: ")
if index >= 0 and index < len(students):
print students[index]
else:
print "Invalid index"
# (v)
students = ["Kamal", "Sanjana"] + students
# (vi)
print students
# (vii)
name = raw_input("Enter a name: ")
if name in students:
students.remove(name)
else:
students.append(name)
# (viii)
rev_students = students[::-1]
# (ix)
print students
print rev_students
# (x)
students.pop()
print students
This exercise mainly uses list operations like
append, remove, pop, indexing, membership test, and slicing.Question 8 (Lab)
8. Use the list of student names from the previous exercise. Create a for loop that asks the user for every name whether they would like to keep the name or delete it. Delete the names which the user no longer wants. Hint: you cannot go through a list using a for loop and delete elements from the same list simultaneously because in that way the for loop will not reach all elements. You can either use a second copy of the list for the loop condition or you can use a second empty list to which you append the elements that the user does not want to delete.
Answer 8 (Lab)
A safe way is to loop through a copy and build a new list.
# Program to keep or delete names
students = ["Ravi", "Meena", "Arjun", "Neha", "Pooja"]
kept = []
for name in students:
choice = raw_input("Keep " + name + "? (yes/no): ")
if choice == "yes":
kept.append(name)
students = kept
print students
This avoids deleting items from the same list while iterating over it.
Question 9 (Lab)
9. Write a function to find product of the element of a list. What happens when the function is called with list of strings?
Answer 9 (Lab)
For numbers:
# Function to find product of numeric elements
def product_list(lst):
p = 1
for item in lst:
p = p * item
return p
Example
# Example usage
print product_list([2, 3, 4])
Output
24
If this function is called with a list of strings, it raises a TypeError, because the logic of multiplying the running product by the next element is meaningful for numbers, but not for multiplying strings by strings.
Question 10 (Lab)
10. Write a program to input NXM matrix and find sum of all even numbers in the matrix.
Answer 10 (Lab)
# Program to find sum of all even numbers in a matrix
m = input("Enter number of rows: ")
n = input("Enter number of columns: ")
a = []
for i in range(m):
row = []
for j in range(n):
value = input("Enter element: ")
row.append(value)
a.append(row)
total = 0
for i in range(m):
for j in range(n):
if a[i][j] % 2 == 0:
total = total + a[i][j]
print "Sum of even numbers =", total
Question 11 (Lab)
11. Write a program to print upper triangle matrix.
Answer 11 (Lab)
The upper triangle contains elements on and above the main diagonal.
# Program to print upper triangle matrix
n = input("Enter order of square matrix: ")
a = []
for i in range(n):
row = []
for j in range(n):
row.append(input("Enter element: "))
a.append(row)
print "Upper triangle matrix is"
for i in range(n):
for j in range(n):
if j >= i:
print a[i][j],
else:
print 0,
print
Question 12 (Lab)
12. Write a program to print lower triangle matrix.
Answer 12 (Lab)
The lower triangle contains elements on and below the main diagonal.
# Program to print lower triangle matrix
n = input("Enter order of square matrix: ")
a = []
for i in range(n):
row = []
for j in range(n):
row.append(input("Enter element: "))
a.append(row)
print "Lower triangle matrix is"
for i in range(n):
for j in range(n):
if j <= i:
print a[i][j],
else:
print 0,
print
Question 13 (Lab)
13. Write a program to find sum of rows and columns of the matrix.
Answer 13 (Lab)
# Program to find row sums and column sums
m = input("Enter number of rows: ")
n = input("Enter number of columns: ")
a = []
for i in range(m):
row = []
for j in range(n):
row.append(input("Enter element: "))
a.append(row)
print "Sum of rows"
for i in range(m):
row_sum = 0
for j in range(n):
row_sum = row_sum + a[i][j]
print row_sum
print "Sum of columns"
for j in range(n):
col_sum = 0
for i in range(m):
col_sum = col_sum + a[i][j]
print col_sum
This program first adds each row separately, then adds each column separately.