Computer Science

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.

Python

Linear Lists

3 Likes

Answer

ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
A = [i for i in ML if i % 2 == 0]
print(A)
[4, 16, 36, 64, 100]

Working

  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.

Answered By

3 Likes


Related Questions