Computer Science
Predict the output :
def even(n):
return n % 2 == 0
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ev = [n for n in list1 if n % 2 == 0]
evp = [n for n in list1 if even(n)]
print(evp)
Python
Linear Lists
2 Likes
Answer
[2, 4, 6, 8]
Working
def even(n)
— This line defines a function namedeven
that takes a parametern
.return n % 2 == 0
— This line returns True if the input numbern
is even (i.e., when n % 2 equals 0), and False otherwise.list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
— This line initializes a list namedlist1
with integers from 1 to 9.ev = [n for n in list1 if n % 2 == 0]
— This line creates a new listev
using a list comprehension. It iterates over each elementn
inlist1
and includesn
inev
if it's even (i.e., if n % 2 == 0).evp = [n for n in list1 if even(n)]
— This line creates a new listevp
using a list comprehension. It iterates over each elementn
inlist1
and includesn
inevp
if the functioneven(n)
returns True for thatn
. Effectively, this also creates a new list from the even numbers oflist1
. Therefore, bothev
andevp
will contain same values.print(evp)
— This line prints the listevp
.
Answered By
1 Like
Related Questions
Predict the output :
ages = [11, 14, 15, 17, 13, 18, 25] print(ages) Elig = [x for x in ages if x in range(14, 18)] print(Elig)
Predict the output :
L1= [x ** 2 for x in range(10) if x % 3 == 0] L2 = L1 L1.append(len(L1)) print(L1) print(L2) L2.remove(len(L2) - 1) print(L1)
Predict the output.
b = [[9, 6], [4, 5], [7, 7]] x = b[:2] x.append(10) print(x)
Predict the output.
b = [[9, 6], [4, 5], [7, 7]] x = b[:2] x[1].append(10) print(x)