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.
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
ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
— This line initializes a listML
.A = [i for i in ML if i % 2 == 0]
— This line uses a list comprehension to create a new listA
. It iterates over each elementi
in the listML
, and only includesi
inA
if i % 2 == 0 is true. This condition checks if the elementi
is even.print(A)
— This line prints the list A, which contains only the even numbers from the listML
.
Related Questions
Change the above code so that it works as stated in previous question.
Modify your previous code so that SqLst stores the doubled numbers in ascending order.
Write equivalent list comprehension for the following code :
target1 = [] for number in source: if number & 1: target1.append(number)
Write equivalent for loop for the following list comprehension :
gen = (i/2 for i in [0, 9, 21, 32]) print(gen)