CBSE Class 12 Computer Science Question 48 of 68

Data Structures - I : Linear Lists — Question 4

Back to all questions
4
Question

Question 4

Consider a list ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write code using a list comprehension that takes the list ML and makes a new list that has only the even elements of this list in it.

Answer
ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
A = [i for i in ML if i % 2 == 0]
print(A)
Output
[4, 16, 36, 64, 100]
Explanation
  1. ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] — This line initializes a list ML.
  2. A = [i for i in ML if i % 2 == 0] — This line uses a list comprehension to create a new list A. It iterates over each element i in the list ML, and only includes i in A if i % 2 == 0 is true. This condition checks if the element i is even.
  3. print(A) — This line prints the list A, which contains only the even numbers from the list ML.