0% found this document useful (0 votes)
1K views

Lists Class 11

The document discusses lists in Python. It defines lists as a type of container in data structures that can store multiple data at the same time, similar to arrays in other languages. Lists can contain heterogeneous elements of different types, including integers, strings, and objects. Lists are mutable, meaning their elements can be changed, and each element has an index corresponding to its position. The document describes how to create and access lists, as well as built-in functions and operators for lists such as membership, comparison, and traversal operations.

Uploaded by

Ashit Mody
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Lists Class 11

The document discusses lists in Python. It defines lists as a type of container in data structures that can store multiple data at the same time, similar to arrays in other languages. Lists can contain heterogeneous elements of different types, including integers, strings, and objects. Lists are mutable, meaning their elements can be changed, and each element has an index corresponding to its position. The document describes how to create and access lists, as well as built-in functions and operators for lists such as membership, comparison, and traversal operations.

Uploaded by

Ashit Mody
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CBSE Term II Computer Science XI 1

CHAPTER 01

Lists in Python
In this Chapter...
l Creating a List l Membership Operators

l Accessing Lists l List Operations

l Traversing a List l Built-in Functions


l Comparison Operators

In Python, list is a type of container in data structures, which Syntax


is used to store multiple data at the same time. List acts as an new_list_name = list (sequence/string)
array which defined other languages such as C++, Java etc. Here, sequence includes tuples, lists etc.
List contains a sequence of heterogeneous elements which
makes it powerful tool in Python. It can store integer, string For example,
as well as object in a single list. It is also useful for >>>A = “PYTHON”
implementing stacks and queues. >>>A1 = list(A)
Lists are mutable which means they can be changed after >>>A1
creation. Each element of a list is assigned a number its [‘P’, ‘Y’, ‘T’, ‘H’, ‘O’, ‘N’]
position or index. The first index is 0, the second index is 1, >>>A = list(“PYTHON”)
the third index is 2 and so on. >>>A
[‘P’, ‘Y’, ‘T’, ‘H’, ‘O’, ‘N’]
Each element in the list has its definite place, which allows
>>>l = (‘P’, ‘Y’, ‘T’, ‘H’, ‘O’, ‘N’)
duplicating of elements in the list with each element having
its own distinct place and credibility. >>>l1 = list(l)
>>>l1
[‘P’, ‘Y’, ‘T’, ‘H’, ‘O’, ‘N’]
Creating a List
Or
In Python, lists can be created to put the elements in square
brackets [ ]. The elements in the list are separated by the list ( ) method is also used to create list of characters and
comma ( ,). integers through keyboard.
For example, For example,
>>> a= list(input (“Enter the elements :”))
a = [ 34 , 76 , 11 , 98 ]
Enter the elements : 234576
b = [‘s’, 3, 6, ‘t’] >>>a
c = [ 34 , 0. 5 , 75 ] [‘2’, ‘3’, ‘4’, ‘5’, ‘7’, ‘6’]
d =[ ] >>>b = list(input(“Enter string : ”))
Enter the string : ARIHANT
Creating a List From an Existing Sequence
>>>b
In Python, list ( ) method is used to create list from an
[‘A’, ‘R’, ‘I’, ‘H’, ‘A’, ‘N’, ‘T’]
existing sequence.
We can create different types of list in Python as follows: >>>l1 [0]
34
(i) Empty List
>>>l1 [6]
Empty list can be created in Python using [ ] . Here is the
76
two ways to create empty list as
>>>l1 [−4]
(a) >>>a = [ ]
‘Python’
>>>print (a)
>>>l1 [3]
Output
12
[]
>>>l1 [−3]
(b) >>>a = list ( )
11
>>>print (a) >>>l1 [9]
Output
It will give an error as IndexError: list index out of range.
[] Because it has 9 elements for which indexing are 0 to 8.
(ii) Mixed Data Types List
Difference between String and List
It can be created to place different data types such as
integers, strings, double etc., into one list. Strings are immutable which means the values provided to
them will not change in the program.
For example,
>>>a = [‘Neha’, ‘Sharma’, 25, 75, 6, 47]
a = “Here is string”
>>>print(a) You can extract value using index, find values but cannot
modify it.
Output
While lists are mutable which means the values of list can be
[‘Neha’, ‘Sharma’, 25, 75, 6, 47] changed at any point of time.
(iii) Nested List a = [1, 2, 3]
Nested lists are list objects where the elements in the lists You have some methods associated with lists like– append,
can be lists themselves. pop, extend etc.
For example, a [1 : 1 ] = [ 5 , 6 ], then ‘a’ will be [1, 5, 6, 2, 3].
>>> A = [‘Neha’, 4, 1, [5, 23, 4], 98]
>> print (A) Traversing a List
Output Traversing a list is a technique to access an individual
[‘Neha’, 4, 1, [5, 23, 4], 98] element of that list. It is also called iterate over a list.
List A contains 5 elements while inner list contains There are multiple ways to iterate over a list in Python.
3 elements ([5, 23, 4]). List A is considered [5, 23, 4] as one These are as follows
element.
Using for loop
Accessing Lists The most common and easy way to traverse a list is with for
loop. for loop is used when you want to traverse each
To access the list’s elements, index number is used. Use the element of a list.
index operator [ ] to access the elements of a list. The index Syntax for variable in list_name:
should be an integer. Index of 0 refers to first element, 1
refers to second element and so on. While the index of −1 For example,
refers to the first last element, −2 refers to the second last a = [‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’]
element and so on. for i in a:
For example, print (i)
l1 = [5, 7, 3, 4, 5, 6, 9, 0, 8] Output
It is called positive index
P
0 1 2 3 4 5 6 7 8
R
5 7 3 4 5 6 9 0 8
O
–9 –8 –7 –6 –5 –4 –3 –2 –1
G
It is called negative index R
A
>>>l1 = [34, 87, ‘Computer’, 12, ‘Python’, 11, 76, M
‘Option’]
Using for loop with range ( ) Greater than (>) operator
There is another method to traverse a list using for loop with It checks whether the left value is greater than that on the
range( ). This is also used len( ) function with range. This right.
method is used when you want to traverse particular For example,
characters in a list.
>>>a = [1, 2, 3, 4]
Syntax for variable in range (len(list_name)): >>>b = [5, 2, 3, 4]
For example,
>>>a > b
a = [‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’]
False
for i in range (len (a)):
print (a [i]) It gives False, which get from first element from two lists as 1
Output > 5.
P
Less than or Equal to (<=) operator
R
O This operator returns True only, if the value on the left is
either less than or equal to that on the right of the operator.
G
R For example,
A >>>a = [2, 4, 3, 7]
M >>>b = [3, 4, 5, 7]
Program to display the elements of list >>>a <= b
True
[‘P’, ‘Y’, ‘T’, ‘H’, ‘O’, ‘N’]
in separate line with their index number. Greater than or Equal to (>=) operator
For example, This operator returns True only, if the value on the left is
list1 = [‘P’, ‘Y’, ‘T’, ‘H’, ‘O’, ‘N’] greater than or equal to that on the right of the operator.
L1 = len (list1)
For example,
for i in range (L1) :
>>>a = [4, 3, 6, 8]
print(“Element :”, list1 [i], “at index
number”, i) >>>b = [2, 5, 4, 3]
>>>a >= b
Output
True
Element : P at index number 0
Element : Y at index number 1 Equal to (= =) operator
Element : T at index number 2
This operator returns True, if the values on either side of the
Element : H at index number 3 operator are equal.
Element : O at index number 4
For example,
Element : N at index number 5
>>>a = [2, 3, 4, 6]
>>>b = [2, [3, 4], 6]
Comparison Operators >>>c = [2, 3, 4, 6]
A comparison operator in Python, also called Python >>>a = = b
relational operator (<, >, = =, ! = ,> = , <=) that compare
False
the values of two operands and returns True or False based
on whether the condition is met. >>>a = = c
True
Comparison operators for comparing lists are as follows

Less than (<) operator Not equal (! =) operator


This operator returns True, if the values on either side of the
It checks if the left value is lesser than that on the right.
operator are unequal.
For example,
For example,
>>>a = [1, 2, 3, 4]
>>>a = [2, 3, 4, 6]
>>>b = [5, 2, 3, 4]
>>>b = [2, [3, 4], 6]
>>>a < b
>>>a != b
True
True
It gives True, which get from first element from two lists as 1
< 5.
Membership Operators >>>l
[43, 56, 34, 22, 34, 98]
These operators are used to find out whether a value is a The (+) operator cannot add list with other type as number
member of a sequence such as string, list, tuple, dictionary or string because this operator is used only with list types.
etc.
For example,
There are two types of membership operator as follows >>>l1 = [2, 5, 7]
>>>l = l1 + 5
in operator
Trackback (most recent call last) :
It evaluates True, if the value in the left operand appears in File “<pyshell#5>”, line 1, in <module>
the sequence found in the right operand. l = l1 + 5
For example, TypeError : can only concatenate list (not
l1 = [45, 76, [3, 98], 6] “int”) to list.
l2 = [60, [23, 43], 65]
For example,
for item in l1:
>>>l1 = [3, 2, 6]
if item in l2:
>>>l = l1 + “Try”
print (“Exist”)
else : Trackback (most recent call last):
print (“Not Exist”) File “<pyshell#1>”, line 1, in <module>
l = l1 + “Try”
Output TypeError : can only concatenate list (not
Not Exist “str”) to list.

not in operator Replicating List


It evaluates True, if the value in the left operand does not You can repeat the elements of the list using (*) operator.
appear in the sequence found in the right operand. This operator is used to replicate the list.
For example, Syntax list = list1 * digit
a = 54 For example,
b = 87 >>>l1 = [3, 2, 6 ]
list1 = [45, 65, 30, 78, 512, 87]
>>>l = l1 * 2
if (a not in list1):
>>>l
print (“a is NOT present in given list”) [3, 2, 6, 3, 2, 6]
else :
print (“a is present in given list”) Slicing of a List
if (b in list1): In Python list, there are multiple ways to print the whole list
print (“b is present in given list”) with all the elements, but to print a specific range of
else : elements from the list, we use slice operation. Slice operation
print (“b is NOT present in given list”) is performed on lists with the use of colon (:).
Output Syntax s = list_name [Start : End]
a is NOT present in given list For example,
b is present in given list >>>list1 = [4, 3, 7, 6, 4, 9, 5, 0, 3, 2]
>>>s = list1 [2 : 5]
List Operations >>>s
[7, 6, 4]
We can perform various operations on list in Python, some of To print elements from beginning to a range use [: Index], to
them are describe below print elements from end use [: –Index] and to print elements
Concatenate Lists from specific index till the end use [Index :].
The most conventional method to perform on the list For example,
concatenaton, the use of (+) operator can easily add the >>>list1 = [4, 3, 7, 6, 4, 9, 5, 0, 3, 2]
whole of one list to other list and hence perform the >>>s = list1 [: 5]
concatenation. >>>s
Syntax list = list1 + list2 [4, 3, 7, 6, 4]
For example, >>>s = list1 [: −6]
>>>l1 = [43, 56, 34] >>>s
>>>l2 = [22, 34, 98] [4, 3, 7, 6]
>>>l = l1 + l2 >>>s = list1 [3 :]
>>>s For example,
[6, 4, 9, 5, 0, 3, 2] >>>l1 = [2, 4, “Try”, 54, “Again”]
You can also print all elements of list in reverse order using >>>l1 [0 : 1] = [34, “Hello”]
[: : −1]. >>>l1
For example, [34, ‘Hello’, 4, ‘Try’, 54, ‘Again’]
>>>s = list1 [: : −1] >>>l1 [4] = [“World”]
>>>s >>>l1
[2, 3, 0, 5, 9, 4, 6, 7, 3, 4] [34, ‘Hello’, 4, ‘Try’, [‘World’], ‘Again’]
Lists are also provide slice steps which used to extract >>>l1 [2] = “Hiiii”
elements from list that are not consecutive. >>>l1
Syntax s = list_name [Start : Stop : Step] [34, ‘Hello’, ‘Hiiii’, ‘Try’, [‘World’],
‘Again’]
It takes three parameters which are as follows
l
Start starting integer where the slicing of the object starts. Built-in Functions
l
Stop integer until which the slicing takes place. The slicing Python has large number of built-in functions and methods
stops at index −1. that make programming easier.
l
Step integer value which determines the increment Some of them are as follows
between each index for slicing.
For example,
(i) append ( )
>>>list1 = [4, 3, 7, 6, 4, 9, 5, 0, 3, 2] This method is used for appending and adding elements to a
>>>l1 = list1 [1 : 10 : 3] list. It is used to add elements to the last position of a list.
>>>l1 Syntax list_name.append (element)
[3, 4, 0] For example,
>>>l2 = list1 [2 : 12 : 2] >>>l1 = [34, 65, 23, 98]
>>>l2 >>>l1.append (76)
[7, 4, 5, 3] >>>l1
>>>l3 = list1 [::4] [34, 65, 23, 98, 76]
>>>l3
[4, 4, 3]
(ii) insert ( )
>>>l4 = list1 [::8] This method is used to insert an element at specified position
>>>l4 in the list. This method takes two arguments : one for index
[4, 3] number and second for element value.
>>>l5 = list1 [3 ::] Syntax list_name. insert (index, element)
>>>l5 For example,
[6, 4, 9, 5, 0, 3, 2] >>>l1 = [34, 65, 23, 98]
For example, >>>l1.insert (3, ‘New’)
>>>l1
Python program to count the number of elements in a given
[34, 65, 23, ‘New’, 98]
range using traversal and multiple line code.
c=0 (iii) extend ( )
l = 40
This method is used to add contents of list 2 to the end of list 1.
r = 80
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70] Syntax listname1. extend (list_name2)
for x in list1 : For example,
if x >= l and x <= r: >>>l1 = [43, ‘Hello’, 56]
c+ = 1 >>>l2 = [‘World’, ‘Try’, 65,77]
print(“List:”, list1) >>>l1.extend(l2)
print(“Elements in a list1:”, c) >>>l1
Output [43, ‘Hello’, 56, ‘World’, ‘Try’, 65, 77]
List : [10, 20, 30, 40, 50, 40, 40, 60, 70] (iv) sum ( )
Elements in a list1 : 6 This method is used to calculate the sum of all the elements
List Modification using Slicing in the list.
List can be modified after it created using slicing. Syntax sum (list_name)
For example, It will return min value of character using ASCII value.
>>>l = [45, 23, 87, 5, 9] >>>l3 = [‘Rahul’, ‘Shiv’, ‘Sandhaya’, ‘Ankit’]
>>>sum (l) >>>min (l3)
169
‘Ankit’
sum ( ) method is used for only numeric values otherwise it
gives an error. (ix) max ( )
>>>l = [45, 23, 87, 5, ‘Hello’]
>>>sum (l)
It is used to return the maximum element out of elements of
list.
Trackback (most recent call last) :
File “<pyshell# 17>”, line 1, in <module> Syntax max (list_name)
sum(l) For example,
TypeError: unsupported operand type (s) for >>>l1 = [34, 76, 89, 33, 54, 65]
+ : ‘int’ and ‘str’ >>>max (l1)
89
(v) count ( ) >>>l2 = [‘t’, ‘e’, ‘E’, ‘U’, ‘v’]
This method is used to calculate total occurrence of given >>>max (l2)
element of list. ‘v’
Syntax list_name. count (element) It will return max value of character using ASCII value.
For example,
>>>list1 = [4, 3, 5, 2, 54, 4, 2, 6, 4, 4, 5]
(x) reverse ( )
>>>list1. count(4) Using the reverse ( ) method, we can reverse the contents of
4 the list object in-place, i.e. we don’t need to create a new list
instead we just copy the existing elements to the original list
(vi) len ( ) in reverse order.
This method is used to calculate the total length of list. Syntax list_name. reverse ( )
Syntax len (list_name) For example,
For example, >>>list1 = [34, 76, 89, 33, 54, 65]
>>>list1 = [4, 3, 5, 2, 54, 4, 2, 6, 4, 4, 5] >>>list1. reverse( )
>>>len (list1) >>>print (list1)
11 [65, 54, 33, 89, 76, 34]
>>>l = [‘Hii’, ‘Hello’, ‘Hey’, ‘Namesty’]
(vii) index () >>>l.reverse ( )
It returns the index of first occurrence. Start and end index >>>print (l)
are not necessary parameters. [‘Namesty’, ‘Hey’, ‘Hello’, ‘Hii’]
Syntax list_name.index (element[, start [, end]])
(xi) pop ( )
For example,
This function is used to remove the element and return last
>>>list1 = [3, ‘New’, 2, 6, ‘Hello’, 2]
value from the list or the given index value.
>>>list1.index (‘Hello’)
4
Syntax list_name.pop (index)
For example,
(viii) min ( ) >>>l1 = [34, 65, 22, 90, 87, 61]
It is used to return the minimum element out of elements of >>>l1.pop (3)
list. 90
Syntax min (list_name) >>>print (l1)
[34, 65, 22, 87, 61]
For example,
>>>l1 = [45, 87, 23, 90, 12] If you do not give any index value, then it will remove last
>>>min (l1) value from the list.
12 >>>l1. pop ( )
61
>>>l2 = [‘A’, ‘B’, ‘c’, ‘e’, ‘a’]
>>>print (l1)
>>>min (l2)
[34, 65, 22, 87]
‘A’
(xii) remove ( ) (xiv) sort ()
This method searches for the given element in the list and This function is used to sort the given list in ascending order.
removes the first matching element. It takes a single element Syntax list _name. sort ( )
as an argument and remove it from the list.
For example,
Syntax list_name. remove (element) >>>list1 = [23, 65, 77, 23, 90, 99, 12]
For example, >>>list1. sort ( )
>>>list1 = [34, 76, 11, 98, 26, 20] >>>print (list1)
>>>list1.remove (11) [12, 23, 23, 65, 77, 90, 99]
>>>list1 >>>list2 = [‘abc’ ‘gdr’, ‘uyt’, ‘abc’,‘nki’]
[34, 76, 98, 26, 20] >>>list2. sort ( )
>>>l1 = [‘Maths’, ‘English’, ‘Hindi’, ‘History’, ‘Science’] >>>print (list2)
>>>l1.remove(‘History’) [‘abc’, ‘abc’, ‘gdr’, ‘nki’, ‘uyt’]
>>>l1 The sort function has an argument called
[‘Maths’, ‘English’, ‘Hindi’, ‘Science’]
reverse = True. This allows us to sort the list elements in
descending order.
If the element (argument) passed to the remove ( ) method
does not exist, ValueError exception is thrown. Syntax list _ name. sort (reverse = True)
>>>l1. remove ( ) For example,
Trackback (most recent call last) : >>>list1 = [23, 65, 77, 23, 90, 99, 12]
File “<pyshell# 11>”, line 1, in <module> >>>list1. sort (reverse = True)
>>>print (list1)
l1.remove ( )
[99, 90, 77, 65, 23, 23, 12]
TypeError : remove ( ) takes exactly one argument (0
given) (xv) list ()
(xiii) clear ( ) It takes sequence types and converts them to lists. This is
used to convert a given sequence (tuple/list/string) into list.
This function is used to remove all the items of a list. This
method will empty the entire list. Syntax list (seq)
For example,
Syntax list_name. clear ( )
>>>t1 = (‘Hello’, 34, 54, ‘xyz’)
For example, >>>list1 = list(t1)
>>>l1 = [23, 45, 87, 12, 98] >>>print (list1)
>>>l1.clear( ) [‘Hello’, 34, 54, ‘xyz’]
>>>l1 >>>t1 = ( )
[] >>>list1 = list (t1)
>>>print (list1)
[]
8 CBSE Term II Computer Science XI

Chapter
Practice
Ans. (c) insert () function is used to insert an element at specified
PART 1 position in the list. This method takes two arguments : one
for index number and second for element value.
Objective Questions Syntax list_name.insert(index, element)
6. Choose the correct option for the following.
l
Multiple Choice Questions l1 = [2, 5, 7]
1. Which value is used to represent the first index of l = l1 + 5
list? print (l)
(a) [7, 10, 12]
(a) 1 (b) 0
(b) [2, 5, 7, 5]
(c) −1 (d) a
(c) [5, 2, 5, 7]
Ans. (b) To access the list’s elements, index number is used. The
index number should be an integer. Index of 0 refers to first (d) TypeError
element, 1 refers to second element and so on. Ans. (d) + operator cannot add list with other type as number or
string because this operator is used only with list types.
2. Choose the output of following Python code. So, it will give TypeError as it can only concatenate list (not
1 = list () “int”) to list.
print ( 1)
(a) [] (b) ()
7. What is the output of following code?
l1 = [3, 2, 6]
(c) [,] (d) Empty
l = l1 * 2
Ans. (a) Empty list can be created in Python using []. To create
empty list, list () is also used.
print (l)
(a) [3, 2, 6, 3, 2, 6]
3. Suppose list (b) [6, 4, 12]
1 = [10, 20, 30, 40, 50, 60, 70] (c) [3, 4, 12]
print( 1[ −3]) (d) TypeError
(a) 30 (b) 50 Ans. (a) * operator can repeat the elements of the list.
(c) 40 (d) Error Syntax list = list1 * digit
Ans. (b) The index of −1 refers to the last element, −2 refers to the
8. Which of the following is true regarding lists in
second last element and so on. Hence, −3 refers to third last
element, i.e. 50.
Python?
(a) Lists are immutable.
4. Choose the output from following code. (b) Size of the lists must be specified before its initialisation.
list1 = [‘A’, ‘R’, ‘I’,‘H’,‘A’,‘N’,‘T’] (c) Elements of lists are stored in contiguous memory
print (list1 [7]) location.
(d) size(list1) command is used to find the size of lists.
(a) T (b) N
(c) A (d) Error Ans. (c) Elements of lists are stored in contiguous memory
location, so it is true regarding lists in Python.
Ans. (d) In the given code, we are trying to access 8th element
from the list which does not exist as we are having total 7 9. Suppose list1 is [56, 89, 75, 65, 99], what is the
elements for which the last index is 6. So, Python will give output of list1 [− 2]?
an IndexError. (a) Error (b) 75
5. Which function is used to insert an element at (c) 99 (d) 65
specified position in the list? Ans. (d) −1 corresponds to the last index in the list, −2 represents
(a) extend () (b) append () the second last element and so on.
So, the output for list1 [− 2] is 65 because 65 is second last
(c) insert () (d) add ()
element of list1.
10. Identify the output of following code. 16. Which method will empty the entire list?
List1=[1, 2, 3, 7, 9] (a) pop() (b) clear()
(c) sort() (d) remove()
L=List1.pop(9)
Ans. (b) clear() method is used to remove all the items of a list.
print(L)
This method will empty the entire list.
(a) Syntax error (b) 9
Syntax
(c) [1, 2, 3, 7] (d) None of these
list_name.clear()
Ans. (a) In pop(9), parentheses put index number instead of
element. In the given list, maximum index number is 4, then 17. Which of the following allows us to sort the list
9 is out of index range. elements in descending order?
11. Suppose list1 is [2445,133,12454,123], what is the (a) reverse = True
output of max(list1)? (b) reverse = False
(a) 2445 (b) 133 (c) sort (descending)
(c) 12454 (d)123 (d) sort. descending
Ans. (c) max() returns the maximum element in the list. From Ans. (a) sort() is used to sort the given list in ascending order. The
given options, 12454 is the element with maximum value. sort() has an argument called reverse = True. This allows us
to sort the list elements in descending order.
12. To add a new element to a list, which command will
we use? 18. Identify the correct output.
(a) list1.add(8) >>>l1 = [34, 65, 23, 98]
(b) list1.append(8) >>>l1. insert(2, 55)
(c) list1.addLast(8) >>> l1
(a) [34, 65, 23, 55] (b) [34, 55, 65, 23, 98]
(d) list1.addEnd(8)
(c) [34, 65, 55, 98] (d) [34, 65, 55, 23, 98]
Ans. (b) We use the function append() to add an element to the
Ans. (d) insert() is used to insert an element at specified position
list.
in the list. This method takes two arguments : one for index
13. What will be the output of the following Python number and second for element value.
code? Syntax
list1=[9, 5, 3, 5, 4] list_name.insert(index, element)
list1[1:2]=[7,8] 19. Find the output from the following code.
print(list1) list1=[2, 5, 4, 7, 7, 7, 8, 90]
(a) [9,5, 3, 7, 8] (b) [9, 7, 8, 3, 5, 4] del list1[2 : 4]
(c) [9,[ 7, 8], 3, 5,4] (d) Error print(list1)
Ans. (b) In the piece of code, slice assignment has been (a) [2, 5, 7, 7, 8, 90] (b) [5, 7, 7, 7, 8, 90]
implemented. The sliced list is replaced by the assigned (c) [2, 5, 4, 8, 90] (d) Error
elements in the list. Ans. (a) del keyword is used to delete the elements from the list.
14. Consider the declaration a=[2, 3, ‘Hello’, 23.0]. 20. Slice operation is performed on lists with the use of
Which of the following represents the data type of (a) semicolon (b) comma
‘a’? (c) colon (d) hash
(a) String (b) Tuple Ans. (c) In Python list, there are multiple ways to print the whole
(c) Dictionary (d) List list with all the elements, but to print a specific range of
Ans. (d) List contains a sequence of heterogeneous elements elements from the list, we use slice operation. Slice
which store integer, string as well as object. It can created to operation is performed on lists with the use of colon (:).
put elements separated by comma (,) in square brackets [].
15. Identify the output of the following Python
l
Case Based MCQs
statement. 21. Suppose that list L1
x = [[1, 2, 3, 4], [5, 6, 7, 8]] [“Hello”, [“am”, “an”], [“that”, “the”, “this”], “you”,
y = x [0] [2] “we”, “those”, “these”]
print(y) Based on the above information, answer the
(a) 3 (b) 4 following questions.
(c) 6 (d) 7
(i) Find the output of len (L1).
Ans. (a) x is a list, which has two sub-lists in it. Elements of first
(a) 10 (b) 7
list will be represented by [0] [i] and elements of second list
will be represented by [1] [i]. (c) 6 (d) Error
(ii) Find the output of L1[3 : 5]. 2. list1 = [45, 77, 87, ‘Next’, ‘Try’, 33, 43]
(a) [“that”, “the”, “this”] (b) [“we”, “those”] Observe the given list and find the answer of
(c) [“you”, “we”] (d) [you, we] questions that follows.
(iii) What will be the output of L1[5:] +L1[2]? (i) list1[−2] (ii) list1[2]
(a) [‘those’, ‘these’, ‘that’, ‘the’, ‘this’] Ans. (i) 33 (ii) 87
(b) [‘those’, ‘these’]
3. Distinguish between string and list.
(c) [‘that’, ‘the’, ‘this’]
Ans. Strings are immutable, which means the values provided to
(d) Error
them will not change in the program. While lists are
(iv) Choose the correct output of mutable which means the values of list can be changed at
print (L1[6:]) any point of time in program.
(a)“those” (b) “these” 4. What is the output of below questions?
(c) “those”, “these” (d) None of these l2 = [75, 43, 40, 36, 28, 82]
(v) Give the correct statement for (i) l2.sort ( )
[‘Hello’, [‘am’, ‘an’], [‘that’, ‘the’, ‘this’], ‘you’, ‘we’, (ii) l2.sort (reverse = True)
‘those’, ‘these’] Ans. (i) [28, 36, 40, 43, 75, 82]
(a) L1[] (b) L1[:] (ii) [82, 75, 43, 40, 36, 28]

(c) all.L1() (d) L1(all) 5. Find the errors.


Ans. (i) (b) len() is used to calculate total occurrence of L1 = [2, 4, 5, 9]
given element of list. L1 is a nested list which contains L2 = L1 * 3
two sub-lists and a sub-list is considered as a single L3 = L1 + 3
element. L4 = L1. pop (5)
(ii) (c) To print a specific range of elements from the list, we Ans. Error 1 L3 = L1 + 3 because + operator cannot add list
use slice operation. Slice operation is performed on lists with other type as number or string.
with the use of colon (:). In L1[3 : 5], slicing start from Error 2 L1.pop (5) parentheses puts index value instead of
index number 3, i.e. ‘you’ to index number (5 − 1) ⇒ 4 i.e. element. In the given list, maximum index value is 3 and 5 is
‘we’. out of index range.
(iii) (a) To print elements from specific index till the end, use
[Index:], so L1[5:] will print from index number 5 till end. 6. What will be the output of the following Python
i.e. ‘those’, ‘these’. To print the element at specified code?
index number use [index_number], so L1[2] will print the a=[13,6,77]
element at index number 2 which is a sub-list and a.append([87])
considered as single element i.e. ‘that’, ‘the’, ‘this’.
a.extend([45,67])
+ operator is used to concatenate the element of list.
print(a)
(iv) (b) To print elements from specific index till the end, use
[Index :], so L1[6:] will print from index number 6 till end Ans. [13,6,77, [87], 45, 67]
i.e. “these”. 7. What will be the output of the following Python
(v) (b) To print the whole list, use [:], so L1[:] will print the
entire list.
code?
a=[18,23,69,[73]]
b=list(a)
PART 2 a[3][0]=110
a[1]=34
Subjective Questions print(b)
Ans. [18, 23, 69, [110]]
l
Short Answer Type Questions 8. Predict the output.
L2 = [4, 5, 3, 1]
1. What is nested list ? Explain with an example. L3 = [3, 4, 11, 2]
Ans. Nested lists are list objects where the elements in the lists
(i) print (L2 + L3)
can be lists themselves.
For example, (ii) print (L2. count (0))
list1=[45,43,12,‘Math’,‘Eng’,[75,34,
(iii) print (L3 [4])
‘A’],5] (iv) L3. remove (11)
Here, list1 contains 7 elements, while inner list contains print (L3)
3 elements. list1 is considered [75, 34, ‘A’] as one element. Ans. (i) [4, 5, 3, 1, 3, 4, 11, 2] (ii) 0
(iii) IndexError (iv) [3, 4, 2]
9. Find the output. (ii) Returns the index of first occurrence.
L = [3, 4, 53, 4, 0, 2, 4, 7, 29] (iii) Adds contents of list2 to the end of list1.
(i) L [2 : 5] (ii) L [: 7] Ans. (i) append ( ) (ii) index ( )
(iii) L [4 :] (iv) [: : −1] (iii) extend ( )
Ans. (i) [53, 4, 0] (ii) [3, 4, 53, 4, 0, 2, 4] 15. Consider the following list myList. What will be
(iii) [0, 2, 4, 7, 29] (iv) [29, 7, 4, 2, 0, 4, 53, 4, 3] the elements of myList after the following two
10. Find the output of the given code. operations:
list2 = [‘A’,‘R’,‘I’,‘H’,‘A’,‘N’,‘T’] myList = [10,20,30,40]
for i in range (len (list2)): (i) myList.append([50,60])
print (list2 [i]) (ii) myList.extend([80,90]) [NCERT]
Ans. A Ans. (i) [10, 20, 30, 40, [50, 60]]
R (ii) [10, 20, 30, 40, 80, 90]
I
H
16. What will be the output of the following code
segment?
A
N myList = [1,2,3,4,5,6,7,8,9,10]
T for i in range(0,len(myList)):
if i%2 == 0:
11. Define the replicating lists with an example. print(myList[i]) [NCERT]
Ans. In Python, you can repeat the elements of the list using (*) Ans. 1
operator. This operator is used to replicate the list.
3
For example,
>>>l1 = [4, 5, 7, 1] 5
>>>l2 = l1 * 2 7
>>>l2 9
[4, 5, 7, 1, 4, 5, 7, 1] 17. What will be the output of the following code
12. Consider the following list and answer the below segment?
questions. (i) myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
l1 = [89, 45, “Taj”, “Qutub”, 93, 42, “Minar”, “Delhi”,
“Agra”] print(myList)

(i) l1 [5 :] (ii) “Qutab” not in l1 (ii) myList = [1,2,3,4,5,6,7,8,9,10]


del myList[:5]
(iii) l1 [−3] (iv) l1 [9] print(myList)
(v) l1[2 : 5] (vi) l1[–2 : 5] (iii) myList = [1,2,3,4,5,6,7,8,9,10]
Ans. (i) [42, ‘Minar’, ‘Delhi’, ‘Agra’] del myList[::2]
(ii) False print(myList) [NCERT]
(iii) ‘Minar’
Ans. (i) [1, 2, 3]
(iv) It gives IndexError because there is index value 0 to 8. (ii) [6, 7, 8, 9, 10]
(v) [‘Taj’, ‘Qutub’, 93] (iii) [2, 4, 6, 8, 10]
(vi) []
18. Differentiate between append() and extend()
13. Predict the output. functions of list. [NCERT]
L1 = [3, 4, 5, 9, 11, 2, 27] Ans. Differences between append() and extend() functions of list
print (L1. index (3)) are
print (max (L1)) append() extend()
print (len (L1)) append() method adds an extend() method concatenates
Ans. Output element to a list. the first list with another list
(or another iterable).
0
27 When append() method adds extend() method iterates over
7 its argument as a single its argument adding each
element to the end of a list, element to the list, extending
14. Write the suitable method’s name for the below the length of the list itself the list.
conditions. will increase by one.
(i) Adds an element in the end of list.
19. Consider a list: Output
list1 = [6,7,8,9] List after pushing all zeroes to end of list :
[4, 7, 9, 8, 2, 4, 9, 0, 0, 0, 0]
What is the difference between the following
operations on list1? 23. Observe the following list and answer the questions
(i) list1 * 2 that follows.
(ii) list1 *= 2 l1 = [45, 65,“The”, [65, “She”, “He”], 90, 12, “This”, 21]
(iii) list1 = list1 * 2 [NCERT] (i) l1 [3 : 4] = [“That”, 54]
Ans. (i) The statement will print the elements of the list twice, (ii) [l1 [4]]
i.e. [6, 7, 8, 9, 6, 7, 8, 9]. However, list1 will not be altered.
(ii) This statement will change the list1 and assign the list (iii) l1 [:7]
with repeated elements, i.e. [6, 7, 8, 9, 6, 7, 8, 9] to list1. (iv) l1 [1 : 2] + l1 [3 : 4]
(iii) This statement will also have same result as the statement Ans. (i) [45, 65, ‘The’, ‘That’, 54, 90, 12, ‘This’, 21]
‘list1 *= 2’. The list with repeated elements, i.e. [6, 7, 8,
(ii) [54]
9, 6, 7, 8, 9] will be assigned to list1.
(iii) [45, 65, ‘The’, ‘That’, 54, 90, 12]
20. What possible output(s) are expected to be (iv) [65, ‘That’]
displayed on screen at the time of execution of the
program from the following code? 24. Write a Python program to find the third largest
number in a entered list.
List = [“Poem”, “Book”, “Pencil”, “Pen”]
y=[]
List1 = List [2 : 3] num = int(input(“Enter number of elements:”))
List[2] = “Scale” for i in range (1, num + 1):
print (List1) x = int (input (“Enter element:”))
Ans. [“Pencil”] y.append(x)
y. sort ()
l
Long Answer Type Questions print(“Third largest element is :”, y[num-3])
Output
21. Write the best suited method’s name for the Enter number of elements : 5
following conditions. Enter element : 76
(i) Insert an element at specified position. Enter element : 45
(ii) Add contents from one list to other. Enter element : 98
(iii) Calculate the total length of list. Enter element : 90
Enter element : 23
(iv) Reverse the contents of the list object.
Third largest element is : 76
Ans. (i) insert ( )
(ii) extend ( ) 25. Write Python program to display all the common
(iii) len ( ) elements of two lists.
(iv) reverse ( ) list1 = [ ]
num = int (input (“Enter number of elements in List1
22. Write a program to move all zeroes to the end of :”))
the list.
for i in range (1, num +1):
list1 = [4, 7, 0, 9, 8, 0, 2, 0, 4, 9, 0] x = int (input(“Enter element:”))
n = len (list1) list1. append (x)
count = 0 list2 = [ ]
for i in range (n): num1 = int (input (“Enter number of elements in List2
if list1[i] ! = 0: :”))
list1 [count] = list1[i] for j in range (1, num1 +1):
count + = 1 y = int (input (“Enter element:”))
while count < n : list2. append (y)
list1 [count] = 0
a_set = set (list1)
count + = 1
b_set = set (list2)
print (“List after pushing all zeroes to if (a_set & b_set):
end of list:”) print (“Common elements are:”, a_set &
print (list1) b_set)
else : (iv) print(stRecord[1])
print (“No common elements”) (v) stRecord[0]=‘Raghav’
Output
28. Write a program to read a list of n integers (positive
Enter number of elements in List1:5
as well as negative). Create two new lists, one
Enter element : 23
having all positive numbers and the other having
Enter element : –45 all negative numbers from the given list. Print all
Enter element : 84 three lists. [NCERT]
Enter element : –12
Ans. List = []
Enter element : 33 Pos = []
Enter number of elements in List2:5 Neg = []
Enter element : 12 Num = int(input(“Enter the Total Number of
Enter element : –45 List Elements : ”))
Enter element : –65 for i in range(1, Num + 1):
Enter element : 41 value = int(input(“Enter the Value of
Enter element : 32 %d Element : ” %i))
Common elements are : {–45} List.append(value)
26. What will be the output of the following for j in range(Num):
statements? if(List[j] >= 0):
Pos.append(List[j])
(i) list1 = [12,32,65,26,80,10]
else:
list1.sort() Neg.append(List[j])
print(list1) print(“Element in Positive List is : ”,
(ii) list1 = [12,32,65,26,80,10] Pos)
sorted(list1) print(“Element in Negative List is : ”,
Neg)
print(list1)
(iii) list1 = [1,2,3,4,5,6,7,8,9,10] 29. Write a program to read a list of n integers and find
their median.
list1[::−2]
Note The median value of a list of values is the middle
list1[:3] + list1[3:] one when they are arranged in order. If there are two
(iv) list1 = [1,2,3,4,5] middle values then take their average. [NCERT]
list1[len(list1)−1] [NCERT] Hint You can use a built-in function to sort the list.
Ans. (i) [10, 12, 26, 32, 65, 80] Ans. num = int(input(“Enter the number of
(ii) [12, 32, 65, 26, 80, 10] elements : ”))
(iii) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list1 = list()
(iv) 5
for i in range(num):
27. The record of a student (Name, Roll No., Marks in x = int(input(“Enter the integer: ”))
five subjects and percentage of marks) is stored in list1.append(x)
the following list: print(“Original list:”,list1)
stRecord = [‘Raman’,‘A-36’,[56,98,99,72,69], 78.8]
list1.sort()
Write Python statements to retrieve the following print(“Sorted list: ”,list1)
information from the list stRecord. c = len(list1)
(i) Percentage of the student if c%2 != 0:
(ii) Marks in the fifth subject med = c//2
(iii) Maximum marks of the student print(“Median: ”,list1[med])
(iv) Roll No. of the student else:
a = list1[c//2]
(v) Change the name of the student from ‘Raman’ to
‘Raghav’ [NCERT] b = list1[(c//2) − 1]
Ans. s=a+b
(i) print(stRecord[3])
med = s/2
(ii) print(stRecord[2][4])
print(“Median: ”, med)
(iii) print(max(stRecord[2]))
30. Write a program to read a list of elements. Modify x = int(input(“Enter the element:
this list, so that it does not contain any duplicate ”))
elements, i.e. all elements occurring multiple times list1.append(x)
in the list should appear only once. [NCERT] print(“Original list: ”,list1)
Ans. list1=[] print()
num=int(input(“Enter the number of pos = int(input(“Enter the position of
elements: ”)) the element you want to delete: ”))
for i in range(num): del list1[pos]
x=int(input(“Enter the element: ”)) print(“List after deletion:”,list1)
list1.append(x) (ii) num = int(input(“Enter the number of elements: ”))
print(“New list: ”) list1 = list()
print(list(set(list1))) for i in range(num):
x = int(input(“Enter the element:
31. Write a program to read a list of elements. Input an
”))
element from the user that has to be inserted in the
list1.append(x)
list. Also, input the position at which it is to be
print(“Original list: ”,list1)
inserted. Write a user defined function to insert the
x = int(input(“Enter the element you
element at the desired position in the list. [NCERT]
want to delete: ”))
Ans. num = int(input(“Enter the number of elements: ”))
list1.remove(x)
list1 = list()
print(“List after deletion: ”,list1)
for i in range(num):
x = int(input(“Enter the element: ”)) 33. In Python, list is a type of container in data
list1.append(x) structures, which is used to store multiple data at
print(“Original list: ”,list1) the same time. It can store integer, string as well as
print() object in a single list. Lists are mutable which
pos = int(input(“Enter the index means they can be changed after creation. Each
position: ”)) element of a list is assigned a number its position or
ele = int(input(“Enter the new element: ”)) index. The first index is 0, the second index is 1, the
list1.insert(pos, ele) third index is 2 and so on.
print() Based on the above information, answer the
print(“New list: ”,list1) following questions.
32. Write a program to read elements of a list. (i) List is defined by which type of bracket?
(i) The program should ask for the position of the (ii) List contains a sequence of what type of
element to be deleted from the list. Write a elements?
function to delete the element at the desired (iii) Lists are mutable. What is it mean?
position in the list. (iv) Which method is also used to create list of
(ii) The program should ask for the value of the characters and integers through keyboard?
element to be deleted from the list. Write a (v) How to represent the first index of list?
function to delete the element of this value from Ans. (i) []
the list. [NCERT] (ii) Heterogeneous
Ans. (i) num = int(input(“Enter the number of (iii) Lists are mutable, which means they can be changed
elements: ”)) after creation
list1 = list() (iv) list ()
for i in range(num): (v) 0
Chapter Test
Multiple Choice Questions 8. What will be the output of following code?
1. What is the output of following code? l = []
list1=[4, 3, 7, 6, 4, 9, 5, 0, 3, 2] for i in range (20, 40) :
l1=list1[1:10:3] if(i % 7 == 0 ) and (i % 5 ! = 0 ) :
print(l1) l . append (str(i))
(a) [3, 7, 6] (b) [3, 4, 0] print (‘.’. join(l))
(c) [3, 6, 9] (d) [7, 9,2] 9. What are the output of below questions?
2. Identify the output of following Python statement. L = [45, 89, 74, 12, 9, 83]
a = [[0, 1, 2], [3, 4, 5, 6]] (i) L.remove ()
b = a [1] [2] (ii) L.remove (12)
print (b)
(a) 2 (b) 1 (c) 4 (d) 5
10. Predict the output.
L1 = [3, 2, 1]
3. Identify the output of following code. L2 = [5, 9, 8]
list1 = [2, 3, 9, 12, 4]
(i) L1 * L2
list1.insert(4, 17)
(ii) L2.sort ( )
list1.insert(2, 23)
print(list1 [−4]) (iii) L1.reverse ( )
(a) 4 (b) 9 (c) 12 (d) 23 11. Write a program to input a list and print it in reverse
4. What will be the output of the following Python code? order.
books = [‘Hindi’, ‘English’, ‘Computer’] 12. Give the output.
if ‘put’ in books: (i) str1 = ‘aeiou’
print(True) list1 = list(str1)
else: print(list1)
print(False)
(ii) list1 = [2, 3, 4, 5]
(a) True (b) False (c) None (d) Error
list1. append(1)
5. Identify the output of the following Python statement. print(list1)
list1=[4,3,7,9,15,0,3,2]
s = list1[2:5] Long Answer Type Questions
print(s) 13. Write the best suited method’s name for the following
(a) [7,9,15,0] (b) [3,7,9,15] conditions.
(c) [7,9,15] (d) [7,9,15,0,3]
(i) Remove the value from the list.
6. What will be the output of following code? (ii) Sort the elements in descending order.
list1=[2, 5, 4, [9, 6], 3] (iii) Calculate the sum of all the elements of list.
list1[3][2] =10
(iv) Return the minimum element out of elements.
print(list1)
(a) [2, 5, 4, [9, 10], 3] (b) [2, 5, 4, 10, [9, 6], 3]
14. Write program to find the minimum and maximum
elements from the entered list.
(c) Index out of range (d) None of these
15. Write program to calculate the sum and mean of the
Short Answer Type Questions elements which are entered by user.
7. What will be the output of the following Python code? 16. Write program to count the frequency of elements in a
list1 = [11, 12, 13, 14, 15] list entered by user.
for i in range (1, 5) :
17. Write program to search for an element with its
list1[i−1] = list1[i] respective index number.
for i in range (0, 5) :
18. Write program to enter the elements of a list and
print(list1[i],end = “ ”) reverse these elements.

Answers
Multiple Choice Questions
1. (b) 2. (d) 3. (b) 4. (b) 5. (c) 6. (c)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy