Sunday, 20 September 2026

Python Coding challenge - Day 1253| What is the output of the following Python Code?

 


Code Explanation:

1️⃣ Creating an Empty List
funcs = []

An empty list is created to store functions.

funcs → []

2️⃣ Starting the Loop
for i in range(3):

range(3) produces:

0, 1, 2

So the loop runs three times.

Iteration i
1st 0
2nd 1
3rd 2

3️⃣ Defining the Function
def f():

A function named f is created during each iteration.

The important point is that the function refers to i, which comes from the surrounding scope.

4️⃣ Returning i
return i

The function doesn't store a separate copy of i.

Instead, it closes over the variable i.

This is the main trick in this question.

5️⃣ Storing the Function
funcs.append(f)

The function object is added to funcs.

After all three iterations:

funcs → [f, f, f]

There are three function objects, but they all refer to the same loop variable i.

6️⃣ Calling All Functions
print([f() for f in funcs])

Now the functions are called.

By this time, the loop has already finished:

i = 2

Therefore each function reads the current value of i:

f() → 2
f() → 2
f() → 2
๐Ÿ”ฅ Why Isn't the Output [0, 1, 2]?

This is called late binding.

The functions don't capture the value of i at each iteration. They look up i when the function is called.

Loop:
i = 0 → create f
i = 1 → create f
i = 2 → create f

After loop:
i = 2

Calls:
f() → 2
f() → 2
f() → 2

✅ Final Output
[2, 2, 2]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (345) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) book (1) Books (359) Bootcamp (14) C (78) C# (12) C++ (83) cloud (1) Course (93) Coursera (305) Cybersecurity (36) data (10) Data Analysis (47) Data Analytics (31) data management (16) Data Science (433) Data Strucures (18) Deep Learning (220) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (9) Excel (24) Finance (13) flask (4) flutter (1) FPL (17) Generative AI (77) Git (13) Google (55) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (404) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (16) PHP (20) Projects (35) Python (1375) Python Coding Challenge (1245) Python Library (5) Python Mathematics (17) Python Mistakes (51) Python Pattern Challenge (7) Python Quiz (637) Python Tips (112) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (55) Udemy (22) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)