PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Hard

Question 14

Q470 - Functions


Look at the code below:



Which snippet would you insert in order for the program

to output the following result:

[2, 3, 4, 5, 6]


  • A

    foo = list(filter(lambda x: x == 0 and x == 1, my_tuple))

  • B

    foo = tuple(filter(lambda x: x-0 and x-1, my_tuple))

  • C

    foo = tuple(filter(lambda x: x > 1, my_tuple))

  • D

    foo = list(filter(lambda x: x-0 and x-1, my_tuple))

Reveal correct answer

Correct answer: D

Explanation

Topics: tuple() list() filter() lambda


Try it yourself:

Explanation:

You need the list() function, because the result is a list.

The filter() function looks for elements for which it is valid

that x - 0 is true and x - 1 is true.

That is both true for all the numbers from 2 to 6

For 0 that is not true, because 0 minus 0 is 0

and 0 evaluates to  False

And for 1 that is not true, because 1 minus 1 is 0

and again 0 evaluates to False


Q470 (Please refer to this number, if you want to write me about this question.)

A. This choice uses the filter function with a lambda function that checks if each element in 'my_tuple' is equal to 0 and equal to 1. Since no element can be both 0 and 1 at the same time, this condition will not filter out any elements, resulting in an incorrect output.

B. This choice uses the filter function with a lambda function that filters out elements from 'my_tuple' where the condition 'x-0 and x-1' evaluates to True. However, this condition does not correctly filter out the consecutive numbers as intended, resulting in an incorrect output.

C. This choice uses the filter function with a lambda function that filters out elements from 'my_tuple' where the condition 'x > 1' is True. This condition filters out elements greater than 1, which does not match the desired output [2, 3, 4, 5, 6].

D. The correct choice uses the filter function with a lambda function that filters out elements from the tuple 'my_tuple' where the condition 'x-0 and x-1' evaluates to True. This condition filters out elements that are not consecutive numbers, resulting in the desired output [2, 3, 4, 5, 6].

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need