KnowledgeBoat Logo
OPEN IN APP

Chapter 7

Lists in Python

Class 11 - Computer Science with Python Preeti Arora



Fill in the Blanks

Question 1

List in Python is classified as a Sequence data type.

Question 2

A list consists of elements of heterogeneous type.

Question 3

Lists are indexed by a/an integer data type.

Question 4

Elements of a list are enclosed in square[] brackets.

Question 5

Lists are mutable, you can update or edit the list.

Question 6

remove() method is used to delete elements from a list if index is not known.

Question 7

pop() method is used to delete elements from a list if index is known.

Question 8

The append() method adds a single item to the existing list at the end.

Question 9

You can compare two lists by using comparison operators.

Question 10

The replication(*) operator replicates a list.

Question 11

The assignment(=) operator creates a reference of the original list that shares the same memory location.

Question 12

The pop() function returns the deleted element of the list.

Question 13

The sort() function arranges the elements of the list either in ascending or descending order.

Question 14

Sorting is to arrange the elements of a list in ascending or descending order.

State True or False

Question 1

Python lists are mutable.

Answer

True

Reason — Lists are called mutable data types in Python because they allow modifications to be made to their elements after the list is created.

Question 2

Lists are depicted through curly brackets only.

Answer

False

Reason — Lists are depicted through square brackets.

Question 3

A list can contain heterogeneous values.

Answer

True

Reason — A list can contain heterogeneous values, meaning it can store elements of different data types.

Question 4

We can create an empty list by the code: L = list()

Answer

True

Reason — In Python, we can create an empty list using built-in function list().

Question 5

A list is stored in memory as integer.

Answer

False

Reason — A list is not stored in memory as a single integer. Instead, it is stored as a collection of references to the elements it contains.

Question 6

The command [1,2,3,4,]<[9,1] will give the output as True.

Answer

True

Reason — In Python, [1, 2, 3, 4] < [9, 1] returns True because list comparison is done element-wise from left to right. The comparison stops and returns True upon finding the first pair where the element in the first list is less than the corresponding element in the second list. Here, 1 < 9 is True, hence the result.

Question 7

List[a:b] will give the elements between a and b.

Answer

False

Reason — List[a:b] will give the elements between a and b-1.

Question 8

The append() function is used to add a value in a list at any place.

Answer

False

Reason — The append() function adds a single item to the end of the list.

Question 9

index() function will return the index of first matched item from the list.

Answer

True

Reason — The index() function in Python returns the index of first matched item from the list.

Question 10

extend() function is used to add multiple list items in a list.

Answer

True

Reason — The extend() method adds one list at the end of another list. In other words, all the items of a list are added at the end of an already created list.

Multiple Choice Questions

Question 1

Consider the following statement:

List = ['h', 'o', 'i']

The length of the above list is:

  1. 5
  2. 3
  3. 0
  4. None of these

Answer

3

Reason — The length of a list in Python is determined by the number of elements it contains. The list ['h', 'o', 'i'] has three elements: 'h', 'o', and 'i'. Therefore, the length of the list is 3.

Question 2

The list L1 contains [3, 4, 5, 6, 6, 8, 0]. What will be the output of the following expression?

print(L1 [-1])
  1. 0
  2. 3
  3. 5
  4. 8

Answer

0

Reason — In Python, negative indexing allows to access list elements starting from the end. The index -1 refers to the last element in the list. For the list L1 = [3, 4, 5, 6, 6, 8, 0], the last element is 0. So the output of print(L1[-1]) is 0.

Question 3

Which of the following statements is correct about list?

  1. List can contain values of mixed data types.
  2. List can contain duplicate values.
  3. A list with no elements is called an empty list.
  4. All of these

Answer

All of these

Reason — Lists in Python can contain values of mixed data types, such as integers, strings, and floats. They can also contain duplicate values, meaning the same value can appear more than once in the list. Additionally, a list with no elements is called an empty list, represented as [].

Question 4

Which operator can be used with list?

  1. in
  2. not in
  3. Both 1 & 2
  4. Arithmetic Operators only

Answer

Both 1 & 2

Reason — The operators in and not in can both be used with lists in Python. The in operator checks if an element is present in the list, while the not in operator checks if an element is not present in the list.

Question 5

Which of the following commands will create a list?

  1. List1=list ()
  2. List1= []
  3. List1=[1,2,3,"a"]
  4. All of these

Answer

All of these

Reason — All of the provided commands will create a list in Python:

  1. List1=list() initializes an empty list using the list constructor.
  2. List1=[] directly initializes an empty list using square brackets.
  3. List1=[1, 2, 3, "a"] initializes a list with mixed data types including integers and a string.

Question 6

What is the use of append() function in list?

  1. It adds an item to the end of the list.
  2. It adds an item at the beginning of the list.
  3. It adds an item anywhere in the list.
  4. All of these

Answer

It adds an item to the end of the list.

Reason — The append() function adds a single item to the end of the list. It does not create a new list, rather it modifies the original list.

Question 7

Select the output of the following expression:

str1 = "pen"
print(list(str1))
  1. ['p', 'e', 'n' ]
  2. [pen]
  3. [p/e/n]
  4. { "pen" }

Answer

['p', 'e', 'n']

Reason — The list() function in Python can be used to convert a string into a list of its individual characters. Therefore, when we execute list(str1) where str1 = "pen", it will convert the string "pen" into a list containing its characters: ['p', 'e', 'n'].

Question 8

The sequential accessing of each of the elements in a list is called:

  1. List Indexing
  2. List Traversal
  3. List Slicing
  4. List Accessing

Answer

List Traversal

Reason — The sequential accessing of each of the elements in a list is called list traversal.

Question 9

Consider the following lists:

L1 = ["this", "is", "a", "list"]
L2 = ["this", "is", "another list"]

Which of the following statements will result in an error?

  1. L1 = L2
  2. L1.copy()
  3. L2.append(1, 2, 3)
  4. L2.pop()

Answer

L2.append(1,2,3)

Reason — The append() method in list takes one argument and adds it as a single element to the end of the list. Using L2.append(1, 2, 3) will result in an error because it provides multiple arguments. The correct statement would be L2.append([1, 2, 3]) to add the entire list [1, 2, 3] as a single element to L2.

Question 10

Consider the following code:

>>>A = [10, 20, 30, 40]
>>>B = A.copy()
>>>A[2] = 50
>>>B

Which of the following will be the elements of list A and B?

  1. A = [10, 20, 50, 40]
    B = [10, 20, 30, 40]
  2. A = [10, 20, 30, 40]
    B = [10, 20, 50, 40]
  3. A = [10, 20, 30, 40, 50]
    B = [10, 20, 50, 40]
  4. A = [10, 20, 40]
    B = [10, 20, 50, 40]

Answer

A=[10, 20, 50, 40]
B=[10, 20, 30, 40]

Reason — The code initializes list A with elements [10, 20, 30, 40]. It then creates a copy of list A named list B using the copy() method. Subsequently, the third element of list A is modified to 50 using A[2] = 50. At this point, B is still [10, 20, 30, 40], because it's a separate list from A. The copy() method does not modify the original list or the modifications made in the new list will not be reflected to the base list.

Question 11

Consider the following lists:

A = [1,2]
B = [1,2]

What will be the output of the following?

print(A==B)
  1. True
  2. False
  3. Error
  4. No output

Answer

True

Reason — When comparing lists A and B using the "==" operator print(A == B), Python checks if both lists have the same elements in the same order. In this case, both lists A and B contain the elements [1, 2], so the comparison A == B evaluates to True.

Question 12

Which of the following functions will return the first occurrence of the specified element in a list?

  1. sort()
  2. value()
  3. index()
  4. Sorted()

Answer

index()

Reason — The index() function in Python returns the index of first matched item from the list.

Question 13

Given A = "[22, 4.88, "India", "T"]" the data type of A is

  1. List
  2. String
  3. Dictionary
  4. Tuple

Answer

String

Reason — In Python, A = "[22, 4.88, "India", "T"]" represents a string because it is enclosed in double quotes (").

Question 14

Find the output of the following code:

number = [1, 5, 7, 0, 4]
print(number[2:3])
  1. [5]
  2. [7]
  3. [7,0]
  4. None of these

Answer

[7]

Reason — The slice number[2:3] extracts a subset of the list starting from index 2 (inclusive) up to, but not including, index 3. In this case, index 2 corresponds to the element 7 in the list number. Therefore, number[2:3] results in [7].

Question 15

What will be the output of the following operation?

L1 = [1,2] 
L2 = [3, 4] 
(L1 + L2)*2
  1. [2, 4, 6, 8]
  2. [1, 2, 3, 4, 1, 2, 3, 4]
  3. [1, 3, 4, 4]
  4. [3, 4, 1, 2]

Answer

[1,2,3,4,1,2,3,4]

Reason — The code initializes two lists, L1 with elements [1, 2] and L2 with elements [3, 4]. It then concatenates these two lists using the + operator, resulting in [1, 2, 3, 4]. Next, it multiplies this concatenated list by 2 using the * operator, which repeats the elements of the list. Therefore, the final output of (L1 + L2) * 2 is [1, 2, 3, 4, 1, 2, 3, 4].

Assertions and Reasons

Question 1

Assertion (A): List in Python is a collection of values of any type.

Reasoning (R): In lists, you can change the elements of a list in place.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true but R is not the correct explanation of A.

Explanation
List in Python is a collection of values of any type such as strings, integers, floats, objects or even a list. Lists in Python are mutable, meaning we can change the elements of a list in place.

Question 2

Consider the given two statements:

T1 = [3, 9, 0, 1, 7]
T2 = [5, 1, 0, 7, 5.5]

Assertion (A): Output of print(len(T1) == len(T2)) is True.

Reasoning (R): Method len() returns the number of elements in the list.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The len() function returns the number of elements in a list. For T1, the length is 5, and for T2, the length is also 5. Since both lists have the same number of elements, len(T1) == len(T2) evaluates to True.

Question 3

Assertion (A): List traversal in Python is done through slicing and using for loop also.

Reasoning (R): Traversal can be done only through forward indexing.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
List traversal in Python can be done using slicing and a for loop. Both methods allow to access and iterate over elements in a list. Traversal in Python lists can be done through both forward and backward indexing.

Question 4

Assertion (A): In Python, list is an immutable collection of data.

Reasoning (R): Mutable means that any change or alteration in data is mentioned in the same place. The updated collection will use the same address for its storage.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is false but R is true.

Explanation
In Python, list is a mutable collection of data, i.e., values in the list can be modified. The term "mutable" means that the objects can be changed in place, and any modifications to the object will use the same memory address.

Question 5

Assertion (A): The position of each element in the list is considered as its index.

Reasoning (R): Indexing in a list can be positive and negative; index is defined using [] brackets.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In Python, an index is a number specifying the position of an element in a list. Indexing in a list can be positive and negative. Positive indexing starts from 0 for the first element, while negative indexing starts from -1 for the last element. Indexing is defined using square brackets ([]).

Question 6

Assertion (A): sort() method sorts the objects of list in ascending order.

Reasoning (R): Defining sort() method with reverse=True as an argument sorts the list elements in descending order.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The sort() function sorts the items of the list, by default in ascending/increasing order. If we want to sort the list in decreasing order, we need to write: sort(reverse = True).

Solutions to Unsolved Questions

Question 1

What are the various ways to create a list?

Answer

The various ways of creating a list are :

  1. Using Square Brackets [].
  2. Using the list() constructor.
  3. Using list comprehensions.
  4. Appending Elements.
  5. Using the extend() method.
  6. Using slicing.

Question 2

What are the similarities between strings and lists?

Answer

Both strings and lists are sequential data types, meaning they store elements in a specific order. They support indexing, allowing access to individual elements using square brackets notation '[]'. Additionally, both strings and lists support slicing, enabling us to extract portions of the sequence using the colon (:) operator. They can also be iterated over using loops such as for loops, facilitating access to each element one by one in the sequence. Furthermore, both strings and lists support the in and not in operators, which check for the presence or absence of a particular element in the sequence.

Question 3

Why are lists called mutable data type?

Answer

Lists are called mutable data types in Python because they allow modifications to be made to their elements after the list is created. This mutability facilitates operations such as adding, removing, or modifying elements within the list even after its initial creation.

Question 4

Define the following functions:

(a) len()

(b) append()

(c) extend()

(d) pop()

(e) remove()

(f) del

(g) sort()

(h) sorted()

(i) copy()

(j) count()

(k) max()

(I) min()

(m) sum()

Answer

(a) len() — The len() function returns the length of the list, i.e., the number of elements in a list.

(b) append() — The append() method adds a single item to the end of the list. It does not create a new list, rather it modifies the original list.

(c) extend() — The extend() method adds one list at the end of another list. In other words, all the items of a list are added at the end of an already created list.

(d) pop() — The pop() method removes the element from the specified index and also returns the element which was removed.

(e) remove() — The remove() function removes the first occurrence of the item from the list. It is useful when we know the element to be deleted but not the index of the element.

(f) del — The del statement removes the specified element from the list but does not return the deleted value.

(g) sort() — The sort() function sorts the items of the list, by default in ascending/increasing order. To sort the list in descending order we use reverse = True parameter. Sorting is done 'in place', i.e., it does not create a new list.

(h) sorted() — The sorted() method takes a list as a parameter and creates a new list consisting of the same elements but arranged in ascending order and returns it as a list. To sort the list in descending order we use reverse = True parameter.

(i) copy() — The copy() function returns a new list stored in a different memory location.

(j) count() — The count() method counts how many times an element has occurred in a list and returns it.

(k) max() — The max() method returns the element with the maximum value from the list.

(I) min() — The min() method returns the element with the minimum value from the list.

(m) sum() — The sum() function in Python is used to calculate the sum of all the elements in list.

Question 5

What is the difference between insert() and append() methods of a list?

Answer

Insert MethodAppend Method
The insert() method is used to add an element at a specific index in the list.The append() method is used to add an element at the end of the list.
The syntax is: list.insert(index, element).The Syntax is: list.append(element).
Example: my_list.insert(2, 'hello') will insert the string 'hello' at index 2 in the list my_list.Example: my_list.append('world') will add the string 'world' at the end of the list my_list.

Question 6

Suppose L = [10, ["few", "facts", "fun"], 3, 'Good']

Consider the above list and answer the following:

(a) L[3:]

(b) L[::2]

(c) L[1:2]

(d) L[1] [1]

Answer

(a) L[3:] — ['Good']

Explanation
The slice L[3:] will include the element at index 3 and any elements that follow it. Since index 3 is the last element, L[3:] will include only ['Good'].

(b) L[::2] — [10, 3]

Explanation
The slice L[::2] means to include every second element from the list, starting from the beginning. This results in selecting the elements at indices 0 and 2, which are 10 and 3.

(c) L[1:2] — [['few', 'facts', 'fun']]

Explanation
The slice L[1:2] selects elements from index 1 up to, but not including, index 2. This means it includes only the element at index 1, which is ["few", "facts", "fun"].

(d) L[1] [1] — facts

Explanation
The expression L[1][1] first accesses the sub-list at index 1, which is ["few", "facts", "fun"], and then accesses the element at index 1 of that sub-list, which is "facts". Therefore, L[1][1] evaluates to "facts".

Question 7

Find the output of the following:

L1=[1, 2, 3]
L2=[4, 5, 6]
print(L1+list ("45") )
print(L1.pop())
L1.remove (2)
print(L1)
L1.extend (L2)
print(L2)

Answer

Output
[1, 2, 3, '4', '5']
3
[1]
[4, 5, 6]
Explanation

In the above code, L1 is defined as [1, 2, 3] and L2 as [4, 5, 6]. The first print(L1 + list("45")) concatenates L1 with the list representation of the string "45", resulting in [1, 2, 3, '4', '5']. The next operation print(L1.pop()) removes and returns the last element of L1, which is 3, printing it. Then, L1.remove(2) removes the element 2 from L1, leaving [1]. Subsequently, L1.extend(L2) appends elements from L2 to L1, modifying it to [1, 4, 5, 6]. Lastly, print(L2) outputs [4, 5, 6], showing that L2 remains unchanged despite being extended into L1.

Question 8(a)

What will be the output of the following statement?

list1 = [12, 32, 65, 26, 80, 10]
list1.sort()
print(list1)
Output
[10, 12, 26, 32, 65, 80]
Explanation

In the above code, list1 is initialized as [12, 32, 65, 26, 80, 10]. The sort() method is then called on list1, which arranges its elements in ascending order. After sorting, list1 becomes [10, 12, 26, 32, 65, 80].

Question 8(b)

What will be the output of the following statement?

list1 = [12, 32, 65, 26, 80, 10]
sorted(list1)
print(list1)

Answer

Output
[12, 32, 65, 26, 80, 10]
Explanation

In the given code, list1 is initialized as [12, 32, 65, 26, 80, 10]. The sorted(list1) function is called, which creates and returns a new list with the elements of list1 sorted in ascending order, but it does not modify the original list1. Since the sorted result is not stored or printed, the next line print(list1) outputs the original unsorted list [12, 32, 65, 26, 80, 10].

Question 8(c)

What will be the output of the following statement?

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list1[::-2]
list1[:3] + list1[3:]

Answer

Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation

In the given code, list1 is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The expression list1[::-2] creates a new list with elements from list1 in reverse order, taking every second element, resulting in [10, 8, 6, 4, 2], but this new list is not stored or used further. The expression list1[:3] + list1[3:] concatenates the first three elements [1, 2, 3] with the rest of the elements [4, 5, 6, 7, 8, 9, 10].

Question 8(d)

What will be the output of the following statement?

list1 = [1, 2, 3, 4, 5]
list1[len(list1)-1]

Answer

Output
[1, 2, 3, 4, 5]
Explanation

In the given code, list1 is initialized as [1, 2, 3, 4, 5]. The len(list1) returns the number of elements in the list, which is 5. The len(list1) - 1 evaluates to 4 (i.e., 5 - 1). The list1[len(list1) - 1] accesses the element at index 4, which is 5. However, since the result is not assigned to any variable or printed, it has no effect on the list.

Question 9

What will be the output of the following code segment?

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(0, len(myList)):
   if i % 2 == 0:
      print (myList[i])

Answer

Output
1
3
5
7
9
Explanation

In the given code, myList is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The for loop iterates over the range of indices from 0 to len(myList)-1. Inside the loop, the if statement checks if the current index i is even by using the modulus operator i % 2 == 0. If the condition is true (i.e., the index is even), it prints the element at that index in myList. As a result, the code prints all the elements at even indices, specifically: 1, 3, 5, 7, and 9.

Question 10(a)

What will be the output of the following code segment?

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[3:]
print(myList)

Answer

Output
[1, 2, 3]
Explanation

In the given code, myList is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The del myList[3:] statement deletes all elements in the list starting from index 3 to the end. This modifies myList to only contain the elements from index 0 to 2. The subsequent print(myList) statement then outputs the modified list [1, 2, 3].

Question 10(b)

What will be the output of the following code segment?

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[:5]
print(myList)

Answer

Output
[6, 7, 8, 9, 10]
Explanation

In the given code, myList is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The del myList[:5] statement deletes all elements in the list from the beginning up to, but not including, index 5. This removes the first five elements (1, 2, 3, 4, 5) from myList. The subsequent print(myList) statement then outputs the modified list, which is [6, 7, 8, 9, 10].

Question 10(c)

What will be the output of the following code segment?

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[::2]
print(myList)

Answer

Output
[2, 4, 6, 8, 10]
Explanation

In the given code, myList is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The del myList[::2] statement deletes elements in the list with a step of 2, starting from the beginning of the list. This means, it removes every second element from myList. Specifically, it deletes elements at indices 0, 2, 4, 6, and 8, which correspond to the values 1, 3, 5, 7, and 9. The subsequent print(myList) statement then outputs the modified list, which is [2, 4, 6, 8, 10].

Question 11

Write the output of the following Python program code:

Str2 = list("Cam@123*")
for i in range(len(Str2)-1):
   if i==5:
      Str2[i] = Str2[i]*2
   elif (Str2 [i].isupper()):
      Str2 [i] = Str2 [i]*2
   elif (Str2 [i].isdigit()):
      Str2 [i] = 'D'
print(Str2)

Answer

Output
['CC', 'a', 'm', '@', 'D', '22', 'D', '*']
Explanation

In the given code, Str2 is initialized as a list of characters from the string "Cam@123*", resulting in ['C', 'a', 'm', '@', '1', '2', '3', '*']. The for loop iterates over the indices of Str2 from 0 to len(Str2) - 1. Within the loop, three conditions modify the elements of Str2: if the index i is 5, the character at Str2[i] is multiplied by 2, if the character is uppercase, it is also multiplied by 2, if the character is a digit, it is replaced with 'D'. After the loop, Str2 becomes ['CC', 'a', 'm', '@', 'D', '22', 'D', '*'], which is printed as the final output.

Question 12

Differentiate between append() and extend() methods of list.

Answer

append()extend()
The append() method adds a single item to the end of the list. The single element can be list, number, strings, dictionary etc.The extend() method adds one list at the end of another list.
The syntax of append() method is list.append(item).The syntax of extend() method is list.extend(list1).
For example:
lst1 = [10, 12, 14]
lst1.append(16)
print(lst1)
Output — [10, 12, 14, 16]
For example:
t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
t1.extend(t2)
print(t1)
Output — ['a', 'b', 'c', 'd', 'e']

Question 13

Write a program to read a list of n integers (positive as well as negative). Create two new lists, one having all positive numbers and the other having all negative numbers from the given list. Print all three lists.

Solution
n = int(input("Enter number of elements in the list: "))
nums = []

print("Enter the elements of the list:")
for i in range(n):
    n1 = int(input("Enter element: "))
    nums.append(n1)

positive = []
negative = []

for num in nums:
    if num < 0:
        negative.append(num)
    else:
        positive.append(num)

print("Original List:", nums)
print("Positive Numbers:", positive)
print("Negative Numbers:", negative)
Output
Enter number of elements in the list: 6
Enter the elements of the list:
Enter element: 1
Enter element: -4
Enter element: 0
Enter element: -3
Enter element: 5
Enter element: 9
Original List: [1, -4, 0, -3, 5, 9]
Positive Numbers: [1, 0, 5, 9]
Negative Numbers: [-4, -3]

Question 14

Write a program to find the largest and the second largest elements in a given list of elements.

Solution
nums = eval(input("Enter the list: "))

first = nums[0]
second = nums[0]

for num in nums[2:]:
    if num > first:
        second = first  
        first = num     
    elif num > second and num != first:
        second = num   

print("Largest element:", first)
print("Second largest element:", second)
Output
Enter the list: [2, 8, 10, 18, 15, 6]
Largest element: 18
Second largest element: 15

Question 15

Write a program to read a list of n integers and find their median.

Note: The median value of a list of values is the middle one when they are arranged in order. If there are two middle values, then take their average.

Hint: Use an inbuilt function to sort the list.

Solution
n = int(input("Enter number of elements in the list: "))
nums = []

print("Enter the elements of the list:")
for i in range(n):
    n1 = int(input("Enter element: "))
    nums.append(n1)
    
nums.sort()
n = len(nums)

if n % 2 == 0:
    mid1 = nums[n // 2 - 1]
    mid2 = nums[n // 2]
    median = (mid1 + mid2) / 2
else:
    median = nums[n // 2]

print("Median of the list is:", median)
Output
Enter number of elements in the list: 6
Enter the elements of the list:
Enter element: 10
Enter element: 20
Enter element: 4
Enter element: 45
Enter element: 99
Enter element: 30
Median of the list is: 25.0


Enter number of elements in the list: 5
Enter the elements of the list:
Enter element: 3
Enter element: 7
Enter element: 9
Enter element: 5
Enter element: 11
Median of the list is: 7

Question 16

What is the basic principle of sorting in insertion sort?

Answer

In insertion sort, for each pass, the correct position for the current element is found by comparing adjacent elements before the current position and sliding larger elements up until an element less than the current element is found.

Question 17

Which sorting is more efficient—bubble sort or insertion sort? Give reason.

Answer

Insertion sort is more efficient than bubble sort because it requires fewer comparisons and swaps. It is adaptive, meaning it performs fewer steps with partially sorted arrays, making it more efficient in such cases.

Question 18

Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements, i.e., all elements occurring multiple times in the list should appear only once.

Solution
nums = eval(input("Enter list: "))

unique_nums = []
for num in nums:
    if num not in unique_nums:
        unique_nums.append(num)

print("The list without duplicates is: ", unique_nums)
Output
Enter list: [11, 34, 67, 8, 66, 11, 8, 5]
The list without duplicates is:  [11, 34, 67, 8, 66, 5]

Question 19

Write a program to create a list of elements. Input an element from the user that has to be inserted in the list. Also, input the position at which it is to be inserted.

Solution
list1 = eval(input("Enter list: "))

new_element = int(input("Enter the element to be inserted: "))

position = int(input("Enter the position at which the element should be inserted: "))
list1.insert(position, new_element)
print("Updated list:", list1)
Output
Enter list: [23, 6, 7, 8, 9]
Enter the element to be inserted: 15
Enter the position at which the element should be inserted: 3
Updated list: [23, 6, 7, 15, 8, 9]

Question 20

Write a program to read elements of a list and do the following:

(a) The program should ask for the position of the element to be deleted from the list and delete the element at the desired position in the list.

(b) The program should ask for the value of the element to be deleted from the list and delete this value from the list.

Solution
nums = eval(input("Enter list: "))

# Option (a): Delete element by position
position = int(input("Enter the position of the element to delete: "))
if 0 <= position < len(nums):
    del nums[position]
    print("List after deletion by position:", nums)
else:
    print("Error: Position out of bounds. Please enter a valid position.")

# Option (b): Delete element by value
value = int(input("Enter the value of the element to delete: "))
if value in nums:
    nums.remove(value)
    print("List after deletion by value:", nums)
else:
    print("Element", value, "not found in the list.")
Output
Enter list: [44, 55, 66, 77, 33, 22]
Enter the position of the element to delete: 3
List after deletion by position: [44, 55, 66, 33, 22]
Enter the value of the element to delete: 22
List after deletion by value: [44, 55, 66, 33]

Question 21

WAP that takes an array S as an argument and add all the odd values and display the sum.

Solution
S = eval(input("Enter the array: "))
total = 0
for value in S:
    if value % 2 != 0:
        total += value
print("Sum of odd values:", total)
Output
Enter the array: [2, 4, 3, 9, 11, 5, 7, 8]
Sum of odd values: 35

Question 22

Write a program to calculate mean of a given list of numbers.

Solution
numbers = eval(input("Enter a list: "))
if len(numbers) == 0:
    print("List is empty, cannot calculate mean.")
else:
    total = sum(numbers)
    n = len(numbers)
    mean = total / n
    print("Mean of the numbers:", mean)
Output
Enter a list: [10, 30, 25, 34, 45, 98]
Mean of the numbers: 40.333333333333336

Question 23

WAP in Python to delete all duplicate elements in a list.

For example,

If list is: [5, 2, 4, -5, 12, 2, 7, 4]

After deleting duplicate elements, new list should be: [5, 2, 4, -5, 12, 7]

Solution
nums = eval(input("Enter a list: "))
unique_nums = []
for num in nums:
    if num not in unique_nums:
        unique_nums.append(num)

print("The list after deleting duplicate elements is: ", unique_nums)
Output
Enter a list: [5, 2, 4, -5, 12, 2, 7, 4]
The list after deleting duplicate elements is:  [5, 2, 4, -5, 12, 7]

Question 24

Write a program to calculate the minimum elements of a given list of numbers.

Solution
l = eval(input("Enter a list: "))
m = min(l)
print("Minimum element in the list:", m)
Output
Enter a list: [1, 4, 65, 34, 23]
Minimum element in the list: 1

Question 25

Write a code to calculate and display total marks and percentage of a student from the given list storing marks of a student.

Solution
marks_list = eval(input("Enter list of marks: "))
total_marks = sum(marks_list)
total_subjects = len(marks_list)
maximum_marks_per_subject = 100 
total_marks_possible = maximum_marks_per_subject * total_subjects
percentage = (total_marks / total_marks_possible) * 100

print("Total Marks:", total_marks)
print("Percentage:", percentage)
Output
Enter list of marks: [85, 90, 78, 92, 88]
Total Marks: 433
Percentage: 86.6

Question 26

WAP to multiply an element by 2 if it is odd index for a given list containing both numbers and strings.

Solution
mixed = eval(input("Enter the list: "))
for index in range(1, len(mixed), 2):
        mixed[index] *= 2  
print("Modified List:", mixed)
Output
Enter the list: [1, 'apple','banana', 5, 'cherry', 7, 'date', 'cherry'] 
Modified List: [1, 'appleapple', 'banana', 10, 'cherry', 14, 'date', 'cherrycherry']

Question 27

WAP to count the frequency of an element in a given list.

Solution
my_list = eval(input("Enter the list: "))
c = int(input("Enter the element whose frequency is to be checked: "))
frequency = my_list.count(c)
print("The frequency of", c, "in the list is: ", frequency)
Output
Enter the list: [1, 2, 3, 4, 1, 2, 1, 3, 4, 5, 1]
Enter the element whose frequency is to be checked: 1
The frequency of 1 in the list is:  4

Question 28

WAP to shift elements of a list so that first element moves to the second index and second index moves to the third index, etc., and last element shifts to the first position.

Suppose list is [10, 20, 30, 40]

After shifting it should look like: [40, 10, 20, 30]

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: [10, 20, 30, 40]
Original List
[10, 20, 30, 40]
Rotated List
[40, 10, 20, 30]

Question 29

An array Num contains the following elements:

3, 25, 13, 6, 35, 8, 14, 45

Write a function to swap the content with next value divisible by 5 so that the resultant array looks like:

25, 3, 13, 35, 6, 8, 45, 14

Solution
Num = [3, 25, 13, 6, 35, 8, 14, 45]
for i in range(len(Num) - 1):
    if Num[i] % 5 != 0 and Num[i + 1] % 5 == 0:
        Num[i], Num[i + 1] = Num[i + 1], Num[i]
print("Resultant List:", Num)
Output
Resultant List: [25, 3, 13, 35, 6, 8, 45, 14]

Question 30

The record of a student (Name, Roll No, Marks in five subjects and percentage of marks) is stored in the following list:

stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]

Write Python statements to retrieve the following information from the list studRecord.

(i) Percentage of the student

(ii) Marks in the fifth subject

(iii) Maximum marks of the student

(iv) Roll No. of the student

(v) Change the name of the student from 'Raman' to 'Raghav'.

Answer

(i) percentage = stRecord[3]

(ii) marks_5 = stRecord[2][4]

(iii) max_marks = max(stRecord[2])

(iv) Roll_No = stRecord[1]

(v) stRecord[0] = 'Raghav'

Question 31

What will be the status of the following list after fourth pass of insertion sort and fourth pass of bubble sort used for arranging elements in ascending order?

12, 14, -54, 64, 90, 24

Answer

Insertion Sort

list = [12, 14, -54, 64, 90, 24]

First pass

[12, 14, -54, 64, 90, 24] → [12, 14, -54, 64, 90, 24] — it will not swap since 12 < 14

Second pass

[12, 14, -54, 64, 90, 24] → [12, -54, 14, 64, 90, 24] — it will swap since -54 < 14
[12, -54, 14, 64, 90, 24] → [-54, 12, 14, 64, 90, 24] — it will swap since -54 < 12

Third pass

[-54, 12, 14, 64, 90, 24] → [-54, 12, 14, 64, 90, 24] — it will not swap since 64 > 14

Fourth pass

[-54, 12, 14, 64, 90, 24] → [-54, 12, 14, 64, 90, 24] — it will not swap since 90 > 64

After the fourth pass of insertion sort, the list is: [-54, 12, 14, 64, 90, 24]

Bubble Sort

list = [12, 14, -54, 64, 90, 24]

First pass — [12, -54, 14, 64, 24, 90]
Second pass — [-54, 12, 14, 24, 64, 90]

First pass

[12, 14, -54, 64, 90, 24] → [12, 14, -54, 64, 90, 24] — it will not swap since 12 < 14
[12, 14, -54, 64, 90, 24] → [12, -54, 14, 64, 90, 24] — it will swap since -54 < 14
[12, -54, 14, 64, 90, 24] → [12, -54, 14, 64, 90, 24] — it will not swap since 14 < 64
[12, -54, 14, 64, 90, 24] → [12, -54, 14, 64, 90, 24] — it will not swap since 64 < 90
[12, -54, 14, 64, 90, 24] → [12, -54, 14, 64, 24, 90] — it will swap since 24 < 90

Second pass

[12, -54, 14, 64, 24, 90] → [-54, 12, 14, 64, 24, 90] — it will swap since -54 < 12
[-54, 12, 14, 64, 24, 90] → [-54, 12, 14, 64, 24, 90] — it will not swap since 12 < 14
[-54, 12, 14, 64, 24, 90] → [-54, 12, 14, 64, 24, 90] — it will not swap since 14 < 64
[-54, 12, 14, 64, 24, 90] → [-54, 12, 14, 24, 64, 90] — it will swap since 24 < 64
[-54, 12, 14, 24, 64, 90] → [-54, 12, 14, 24, 64, 90] — it will not swap since 64 < 90

Since the list is sorted after the second pass: [−54, 12, 14, 24, 64, 90], there is no need to proceed to the third and fourth pass.

Question 32

Write the steps to arrange the following elements using insertion sort:

12, 5, 14, 8, 3, 54, 25, 10, 27, 30

Answer

list = [12, 5, 14, 8, 3, 54, 25, 10, 27, 30]

First pass

[12, 5, 14, 8, 3, 54, 25, 10, 27, 30] → [5, 12, 14, 8, 3, 54, 25, 10, 27, 30] — it will swap since 5 < 12

Second pass

[5, 12, 14, 8, 3, 54, 25, 10, 27, 30] → [5, 12, 14, 8, 3, 54, 25, 10, 27, 30] — it will not swap since 12 < 14

Third pass

[5, 12, 14, 8, 3, 54, 25, 10, 27, 30] → [5, 12, 8, 14, 3, 54, 25, 10, 27, 30] — it will swap since 8 < 14
[5, 12, 8, 14, 3, 54, 25, 10, 27, 30] → [5, 8, 12, 14, 3, 54, 25, 10, 27, 30] — it will swap since 8 < 12

Fourth pass

[5, 8, 12, 14, 3, 54, 25, 10, 27, 30] → [5, 8, 12, 3, 14, 54, 25, 10, 27, 30] — it will swap since 3 < 14
[5, 8, 12, 3, 14, 54, 25, 10, 27, 30] → [5, 8, 3, 12, 14, 54, 25, 10, 27, 30] — it will swap since 3 < 12
[5, 8, 3, 12, 14, 54, 25, 10, 27, 30] → [5, 3, 8, 12, 14, 54, 25, 10, 27, 30] — it will swap since 3 < 8
[5, 3, 8, 12, 14, 54, 25, 10, 27, 30] → [3, 5, 8, 12, 14, 54, 25, 10, 27, 30] — it will swap since 3 < 5

Fifth pass

[3, 5, 8, 12, 14, 54, 25, 10, 27, 30] → [3, 5, 8, 12, 14, 54, 25, 10, 27, 30] — it will not swap since 14 < 54

Sixth pass

[3, 5, 8, 12, 14, 54, 25, 10, 27, 30] → [3, 5, 8, 12, 14, 25, 54, 10, 27, 30] — it will swap since 25 < 54

Seventh pass

[3, 5, 8, 12, 14, 25, 54, 10, 27, 30] → [3, 5, 8, 12, 14, 25, 10, 54, 27, 30] — it will swap since 10 < 54
[3, 5, 8, 12, 14, 25, 10, 54, 27, 30] → [3, 5, 8, 12, 14, 10, 25, 54, 27, 30] — it will swap since 10 < 25
[3, 5, 8, 12, 14, 10, 25, 54, 27, 30] → [3, 5, 8, 12, 10, 14, 25, 54, 27, 30] — it will swap since 10 < 14
[3, 5, 8, 12, 10, 14, 25, 54, 27, 30] → [3, 5, 8, 10, 12, 14, 25, 54, 27, 30] — it will swap since 10 < 12

Eighth pass

[3, 5, 8, 10, 12, 14, 25, 54, 27, 30] → [3, 5, 8, 10, 12, 14, 25, 27, 54, 30] — it will swap since 27 < 54

Ninth pass

[3, 5, 8, 10, 12, 14, 25, 27, 54, 30] → [3, 5, 8, 10, 12, 14, 25, 27, 30, 54] — it will swap since 30 < 54

After the Ninth pass of insertion sort, the list is: [3, 5, 8, 10, 12, 14, 25, 27, 30, 54]

PrevNext