KnowledgeBoat Logo

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

  1. def even(n) — This line defines a function named even that takes a parameter n.
  2. return n % 2 == 0 — This line returns True if the input number n is even (i.e., when n % 2 equals 0), and False otherwise.
  3. list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] — This line initializes a list named list1 with integers from 1 to 9.
  4. ev = [n for n in list1 if n % 2 == 0] — This line creates a new list ev using a list comprehension. It iterates over each element n in list1 and includes n in ev if it's even (i.e., if n % 2 == 0).
  5. evp = [n for n in list1 if even(n)] — This line creates a new list evp using a list comprehension. It iterates over each element n in list1 and includes n in evp if the function even(n) returns True for that n. Effectively, this also creates a new list from the even numbers of list1. Therefore, both ev and evp will contain same values.
  6. print(evp) — This line prints the list evp.

Answered By

1 Like


Related Questions