Friday , September 20 2024

Look at the following code: numbers = [i*i for i in range(5)] # Insert line of code here. print(foo) Which line would you insert in order for the program to produce the expected output? Output[1, 9]

Questions BankCategory: Python Essentials 2Look at the following code: numbers = [i*i for i in range(5)] # Insert line of code here. print(foo) Which line would you insert in order for the program to produce the expected output? Output[1, 9]
Look at the following code:

numbers = [i*i for i in range(5)]
# Insert line of code here.
print(foo)

Which line would you insert in order for the program to produce the expected output?

Output[1, 9]
  • foo = list(filter(lambda x: x % 2, numbers))
  • foo = list(map(lambda x: x // 2, numbers))
  • foo = list(filter(lambda x: x / 2, numbers))
  • foo = list(map(lambda x: x % 2, numbers))

Explanation: In order to obtain the expected output, the filter() function is used. The filter(function, list) function creates a copy of the list elements which cause the function function to return True. The filter() function’s result is a generator providing the new contents element by element.

Let’s analyze the code:

  • The following list is created with the use of a list comprehension mechanism: [0, 1, 4, 9, 16].
  • After inserting the correct line, that is foo = list(filter(lambda x: x % 2, numbers)), the lambda function lambda x: x % 2 and the numbers list are provided as the filter() function arguments. The lambda function performs the operation x: x % 2 on each element of the numbers list, and the filter() function filters out the elements that evaluate to 0, that is, False (0, 4, 16), and makes a copy of the elements that evaluate to 1, which is True (1, 9). The result is converted to a list, and passed to the foo object.

More Questions: Python Essentials 2 (PE2) Course Final Test