List Manipulation QB
List Manipulation QB
# removes element at
# index 1 i.e. 2 from
# the list and stores
# in variable a
a = pop(1)
The append() function can add a single The extend() function can add multiple elements from a list
element to the end of a list. supplied to it as argument.
After append(), the length of the list will After extend() the length of the list will increase by the
increase by 1 element only. length of the list given as argument to extend()
Question 16
Do functions max( ), min( ), sum( ) work with all types of lists.
Answer
No, for max() and min() to work on a list, the list must contain all elements of same type
(non-complex type) and for sum() to work, the list must contain the elements which can be
added such as numbers.
Question 17
What is the difference between sort( ) and sorted( )?
Answer
sort( ) sorted( )
It modifies the list it is called on. That is, It creates a new list containing a sorted version of the list
the sorted list is stored in the same list; a passed to it as argument. It does not modify the list passed
new list is not created. as a parameter.
It does not return anything (no return It returns a newly created sorted list. It does not change th
value). It modifies the list in place. passed sequence.
Type B: Application Based Questions
Question 1
What is the difference between following two expressions, if lst is given as [1, 3, 5]
(i) lst * 3 and lst *= 3
(ii) lst + 3 and lst += [3]
Answer
(i)
lst * 3 will give [1, 3, 5, 1, 3, 5, 1, 3, 5] but the original lst will remains unchanged, it will be
[1, 3, 5] only.
lst *= 3 will also give [1, 3, 5, 1, 3, 5, 1, 3, 5] only but it will assign this result back to lst so lst
will be changed to [1, 3, 5, 1, 3, 5, 1, 3, 5].
(ii)
lst + 3 will cause an error as both operands of + operator should be of same type but here
one operand is list and the other integer.
lst += [3] will add 3 to the end of lst so lst becomes [1, 3, 5, 3].
Question 2
Given two lists:
L1 = ["this", 'is', 'a', 'List'], L2 = ["this", ["is", "another"], "List"]
Which of the following expressions will cause an error and why?
1. L1 == L2
2. L1.upper( )
3. L1[3].upper( )
4. L2.upper( )
5. L2[1].upper( )
6. L2[1][1].upper( )
Answer
L1.upper( ) will cause an error as upper() method can be called with Strings not Lists.
L2.upper( ) will cause an error as upper() method can be called with Strings not Lists.
L2[1].upper( ) will cause an error as L2[1] is a list — [ "is", "another"] and upper()
method cannot be called on Lists.
Question 3
From the previous question, give output of expressions that do not result in error.
Answer
L1 == L2 gives output as false because L1 is not equal to L2.
L1[3].upper( ) gives output as 'LIST' because L1[3] is 'List' and upper() function
converts it to uppercase.
L2[1][1].upper( ) gives output as 'ANOTHER' because L2[1] ["is", "another"] and L2[1]
[1] is "another". upper() function converts it to uppercase.
Question 4
Given a list L1 = [3, 4.5, 12, 25.7, [2, 1, 0, 5], 88]
1. Which list slice will return [12, 25.7, [2, 1, 0, 5]]?
2. Which expression will return [2, 1, 0, 5]?
3. Which list slice will return [[2, 1, 0, 5]]?
4. Which list slice will return [4.5, 25.7, 88]?
Answer
1. L1[2:5]
2. L1[4]
3. L1[4:5]
4. L1[1::2]
Question 5
Given a list L1 = [3, 4.5, 12, 25.7, [2, 1, 0, 5], 88], which function can change the list to:
1. [3, 4.5, 12, 25.7, 88]
2. [3, 4.5, 12, 25.7]
3. [ [2, 1, 0, 5], 88]
Answer
1. L1.pop(4)
2. del L1[4:6]
3. del L1[:4]
Question 6
What will the following code result in?
L1 = [1, 3, 5, 7, 9]
print (L1 == L1.reverse( ) )
print (L1)
Answer
Output
False
[9, 7, 5, 3, 1]
Explanation
L1 is not equal to its reverse so L1 == L1.reverse( ) gives False but L1.reverse( ) reverses L1 in
place so after that statement executes, L1 becomes [9, 7, 5, 3, 1].
Question 7
Predict the output:
my_list= [ 'p', 'r', 'o', 'b', 'l' , 'e', 'm']
my_list[2:3] = []
print(my_list)
my_list[2:5] = []
print(my_list)
Answer
Output
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'r', 'm']
Explanation
my_list[2:3] = [] removes element at index 2 of my_list so it becomes ['p', 'r', 'b', 'l', 'e', 'm'].
my_list[2:5] removes elements at indexes 2, 3, and 4 so now my_list becomes ['p', 'r', 'm'].
Question 8
Predict the output:
List1 = [13, 18, 11, 16, 13, 18, 13]
print(List1.index(18))
print(List1.count(18))
List1.append(List1.count(13))
print(List1)
Answer
Output
1
2
[13, 18, 11, 16, 13, 18, 13, 3]
Explanation
List1.index(18) gives the first index of element 18 in List1 which in this case is 1.
List1.count(18) returns how many times 18 appears in List1 which in this case is 2.
List1.count(13) returns 3 as 13 appears 3 times in List1. List1.append(List1.count(13)) add
this 3 to the end of List1 so it becomes [13, 18, 11, 16, 13, 18, 13, 3].
Question 9
Predict the output:
Odd = [1,3,5]
print( (Odd +[2, 4, 6])[4] )
print( (Odd +[12, 14, 16])[4] - (Odd +[2, 4, 6])[4] )
Answer
Output
4
10
Explanation
Odd + [2, 4, 6] will return [1, 3, 5, 2, 4, 6]. The element at index 4 of this list is 4 so the first
output is 4. (Odd +[12, 14, 16])[4] is 14 and (Odd +[2, 4, 6])[4] is 4. 14 - 4 = 10 which is the
second output.
Question 10
Predict the output:
a, b, c = [1,2], [1, 2], [1, 2]
print(a == b)
print (a is b)
Answer
Output
True
False
Explanation
As corresponding elements of list a and b are equal hence a == b returns True. a is b returns
False as a and b are two different list objects referencing two different memory locations.
Question 11
Predict the output of following two parts. Are the outputs same? Are the outputs different?
Why?
(a)
L1, L2 = [2, 4] , [2, 4]
L3 = L2
L2[1] = 5
print(L3)
(b)
L1, L2 = [2, 4] , [2, 4]
L3 = list(L2)
L2[1] = 5
print(L3)
Answer
Output of part (a) is:
[2, 5]
Output of part (b) is:
[2, 4]
As we can see, outputs of the two parts are different. The reason is that in part (a), the
statement L3 = L2 creates a shallow copy of L2 in L3 i.e. both the variables L2 and L3 point to
the same list. Hence, when element at index 1 of L2 is changed to 5, that change is visible in
L3 also. On the other hand in part (b), the statement L3 = list(L2) creates a true copy (also
called deep copy) of L2 so L3 points to a different list in memory which has the same
elements as L2. Now when element at index 1 of L2 is changed to 5, that change is not
visible in L3.
Question 12
Find the errors:
1. L1 = [1, 11, 21, 31]
2. L2 = L1 + 2
3. L3 = L1 * 2
4. Idx = L1.index(45)
Answer
Line 2 — L2 = L1 + 2 will result in error as one element of + is a list and other is an
integer. In Python, operands of + operator should be of same type.
Line 4 — Idx = L1.index(45) will cause an error as 45 is not present in the list L1.
Question 13a
Find the errors:
L1 = [1, 11, 21, 31]
An = L1.remove(41)
Answer
L1.remove(41) will cause an error as 41 is not present in L1.
Question 13b
Find the errors:
L1 = [1, 11, 21, 31]
An = L1.remove(31)
print(An + 2)
Answer
An + 2 will cause an error because remove() function does not return the removed element
so An will be None. Addition operator (+) does not allow any of its operands to be None
hence, it will raise a TypeError.
Question 14a
Find the errors:
L1 = [3, 4, 5]
L2 = L1 * 3
print(L1 * 3.0)
print(L2)
Answer
The line print(L1 * 3.0) causes an error as Python does not allow multiplying a list with a
non-int number and 3.0 is of float type.
Question 14b
Find the errors:
L1 = [3, 3, 8, 1, 3, 0, '1', '0', '2', 'e', 'w', 'e', 'r']
print(L1[: :-1])
print(L1[-1:-2:-3])
print(L1[-1:-2:-3:-4])
Answer
The line print(L1[-1:-2:-3:-4]) causes an error as its syntax is invalid. The correct syntax for
slicing a list is L1[start:stop:step].
Question 15
What will be the output of following code?
x = ['3', '2', '5']
y = ''
while x:
y = y + x[-1]
x = x[:len(x) - 1]
print(y)
print(x)
print(type(x), type(y))
Answer
Output
523
[]
<class 'list'> <class 'str'>
Explanation
The loop while x will continue executing as long as the length of list x is greater than 0. y is
initially an empty string. Inside the loop, we are adding the last element of x to y and after
that we are removing the last element of x from x. So, at the end of the loop y becomes 523
and x becomes empty. Type of x and y are list and str respectively.
Question 16
Complete the code to create a list of every integer between 0 and 100, inclusive, named
nums1 using Python, sorted in increasing order.
Answer
nums1 = list(range(101))
Question 17
Let nums2 and nums3 be two non-empty lists. Write a Python command that will append
the last element of nums3 to the end of nums2.
Answer
nums2.append(nums3[-1])
Question 18
Consider the following code and predict the result of the following statements.
bieber = ['om', 'nom', 'nom']
counts = [1, 2, 3]
nums = counts
nums.append(4)
1. counts is nums
2. counts is add([1, 2], [3, 4])
Answer
1. Output is True as both nums and counts refer to the same list.
2. This will cause an error as add function is not defined in the above code.
Question 19
What is the output of the following code?
numbers = list(range(0, 51, 4))
results = []
for number in numbers:
if not number % 3:
results.append(number)
print(results)
Answer
Output
[0, 12, 24, 36, 48]
Explanation
list(range(0, 51, 4)) will create a list from 0 to 48 with a step of 4 so numbers will be [0, 4, 8,
12, 16, 20, 24, 28, 32, 36, 40, 44, 48]. For loop will traverse the list one number at a time. if
not number % 3 means if number % 3 is equal to 0 i.e. number is divisible by 3. The numbers
divisible by 3 are added to the results list and after the loop results list is printed.
Question 20
Following code prints the given list in ascending order. Modify the code so that the
elements are printed in the reverse order of the result produced by the given code.
numbers = list(range(0, 51, 4))
i=0
while i < len(numbers):
print(numbers[i] , end = " ")
i += 3
# gives output as : 0 12 24 36 48
Answer
numbers = list(range(0, 51, 4))
i = len(numbers) - 1
while i >= 0:
print(numbers[i] , end = " ")
i -= 3
Output
48 36 24 12 0
Type C: Programming Practice/Knowledge based Questions
Question 1
Write a program to increment the elements of a list with a number.
Solution
lst = eval(input("Enter a list: "))
print("Existing list is:", lst)
for i in range(len(lst)):
lst[i] += n
for i in range(len(l)):
if l[i] > 10:
l[i] = 10
for i in range(len(l1)):
l2.append(l1[i][1:])
if n in l:
print(n, "found at index", l.index(n))
else :
print(n, "not found in list")
Output
Enter list: [1, 3, 15, 8, 20]
Enter number to search: 15
15 found at index 2
=====================================
for i in range(50):
l.append(i)
print("Created List:")
print(l)
Output
Created List:
['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg', 'hhhhhhhh', 'iiiiiiiii', 'jjjjjjjjjj', 'kkkkkkkkkkk',
'llllllllllll', 'mmmmmmmmmmmmm', 'nnnnnnnnnnnnnn', 'ooooooooooooooo',
'pppppppppppppppp', 'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr', 'sssssssssssssssssss',
'tttttttttttttttttttt', 'uuuuuuuuuuuuuuuuuuuuu',
'vvvvvvvvvvvvvvvvvvvvvv', 'wwwwwwwwwwwwwwwwwwwwwww',
'xxxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzzzzzzzzzzzz']
Question 8
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].
Solution
print("Enter two lists of same size")
L = eval(input("Enter first list(L): "))
M = eval(input("Enter second list(M): "))
N = []
for i in range(len(L)):
N.append(L[i] + M[i])
print("List N:")
print(N)
Output
Enter two lists of same size
Enter first list(L): [3, 1, 4]
Enter second list(M): [1, 5, 9]
List N:
[4, 6, 13]
Question 9
Write a program rotates the elements of a list so that the element at the first index moves
to the second index, the element in the second index moves to the third index, etc., and the
element in the last index moves to the first index.
Solution
l = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
Output
Enter the list: [8, 10, 13, 25, 7, 11]
Original List
[8, 10, 13, 25, 7, 11]
Rotated List
[11, 8, 10, 13, 25, 7]
Question 10
Write a program that reads the n to display nth term of Fibonacci series.
The Fibonacci sequence works as follows:
element 0 has the value 0
element 1 has the value 1
every element after that has the value of the sum of the two preceding elements
The beginning of the sequence looks like:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The program prompts for element and prints out the value of that element of the Fibonacci
sequence.
Thus:
input 7, produces 13
input 9, produces 34
Hints:
A Don't try to just type out the entire list. It gets big very fast. Element 25 is 75205. Element
100 is 354224848179261915075. So keep upper limit of n to 20.
Solution
n = int(input("Enter n: "))
if (n > 20):
print("n should be less than or equal to 20")
else :
a=0
b=1
c=a+b
for i in range(3, n + 1):
a=b
b=c
c=a+b
=====================================
Enter n: 9
9 term of Fibonacci series = 34
=====================================
Enter n: 25
n should be less than or equal to 20
Question 11a
Write programs as per following specifications:
'''Print the length of the longest
string in the list of strings str_list.
Precondition : the list will contain
at least one element.'''
Solution
l = eval(input("Enter list of strings: "))
largeIdx = 0
largeLen = 0
for i in range(len(l)):
length = len(l[i])
if length > largeLen:
largeLen = length
largeIdx = i
l2 = []
for i in l1:
l2.append(i + num)
print("New list:")
print(l2)
Output
Enter list of numbers: [10, 20, 30, 40, 50]
Enter the number to sum with (num): 15
New list:
[25, 35, 45, 55, 65]
Question 12
Write a program to read two lists num and denum which contain the numerators and
denominators of same fractions at the respective indexes. Then display the smallest fraction
along with its index.
Solution
num = eval(input("Enter numerators list: "))
denum = eval(input("Enter denominators list: "))
small = 0.0
smallIdx = 0
for i in range(len(num)):
t = num[i] / denum[i]
if t < small:
small = t
smallIdx = i
l = dedup + dup
print("Modified List:")
print(l)
Output
Enter the list: [20, 15, 18, 15, 7, 18, 12, 13, 7]
Modified List:
[20, 15, 18, 7, 12, 13, 15, 18, 7]
Question 15
Write a program to compare two equal sized lists and print the first index where they differ.
Solution
print("Enter two equal sized lists")
l1 = eval(input("Enter first list: "))
l2 = eval(input("Enter second list: "))
for i in range(len(l1)):
if l1[i] != l2[i]:
print("Lists differ at index", i)
break;
else:
print("Lists are equal")
Output
Enter two equal sized lists
Enter first list: [80, 60, 50, 40, 30]
Enter second list: [80, 60, 55, 42, 30]
Lists differ at index 2
=====================================