Courseiva
Functions, Tuples, Dictionaries and ExceptionshardMultiple ChoiceObjective-mapped

PCEP Practice Question: Functions, Tuples, Dictionaries and Exceptions

Exhibit

funcs = []
for i in range(3):
    funcs.append(lambda: i)

for f in funcs:
    print(f(), end=' ')

Refer to the exhibit. What is the output when the code is executed?

⚠ Common exam trap

The trap is that candidates might assume the loop prints each element of the tuple (0, 1, 2) sequentially, but the code prints the element at index 2 (the third element) each time, resulting in three copies of 2.

Answer choices

Why each option matters

Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.

Correct answer & explanation

2 2 2

The code defines a tuple `t = (0, 1, 2)`. The `for` loop iterates over the tuple, but each iteration prints `t[2]`, which is the third element (index 2) with value 2. Since the value is constant, it prints '2' three times. Hence the output is '2 2 2'.

Answer analysis

Option-by-option breakdown

For each option: why learners choose it and why it is or isn't the right answer here.

  • 0 1 2

    Why it's wrong here

    Late binding causes all lambdas to see the final value of i.

  • 0 0 0

    Why it's wrong here

    i is not frozen at each iteration.

  • 2 2 2

    Why this is correct

    Correct: i is 2 at the end of the loop, so all functions return 2.

  • 3 3 3

    Why it's wrong here

    i ranges from 0 to 2, final value is 2, not 3.

About these practice questions

One of 498 original PCEP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →

How Courseiva writes practice questions · Editorial policy

JA

Written by Johnson Ajibi, MSc IT Security

Senior Network & Security Engineer · founder of Courseiva

This PCEP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCEP exam.