Sunday, 1 March 2026

Python Coding Challenge - Question with Answer (ID -010326)

 


🔍 Step 1: What does the loop do?

for i in range(3):

range(3) → 0, 1, 2

So the loop runs 3 times.

Each time we append:

lambda x: x + i

So it looks like we are creating:

x + 0
x + 1
x + 2

But… ❗ that’s NOT what actually happens.


🔥 The Important Concept: Late Binding

Python does not store the value of i at the time the lambda is created.

Instead, the lambda remembers the variable i itself, not its value.

This is called:

🧠 Late Binding

The value of i is looked up when the function is executed, not when it is created.


 After the Loop Finishes

After the loop ends:

i = 2

The loop stops at 2, so the final value of i is 2.

Now your list funcs contains 3 functions, but all of them refer to the SAME i.

Effectively, they behave like:

lambda x: x + 2
lambda x: x + 2
lambda x: x + 2

🚀 Now Execution Happens

[f(10) for f in funcs]

Each function is called with 10.

Since i = 2:

10 + 2 = 12

For all three functions.


✅ Final Output

[12, 12, 12]

🎯 How To Fix It (Capture Current Value)

If you want expected behavior (10, 11, 12), do this:

funcs = []

for i in range(3):
funcs.append(lambda x, i=i: x + i)

print([f(10) for f in funcs])

Why this works?

i=i creates a default argument, which stores the current value of i immediately.

Now output will be:

[10, 11, 12]

💡 Interview Tip

If someone asks:

Why does Python give [12,12,12]?

Say confidently:

Because of late binding in closures — lambdas capture variables, not values.

Book: 🐍 50 Python Mistakes Everyone Makes ❌ 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (212) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (9) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (86) Coursera (300) Cybersecurity (29) data (2) Data Analysis (26) Data Analytics (20) data management (15) Data Science (309) Data Strucures (16) Deep Learning (127) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (18) Finance (10) flask (3) flutter (1) FPL (17) Generative AI (65) Git (10) Google (50) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (254) Meta (24) MICHIGAN (5) microsoft (10) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1260) Python Coding Challenge (1054) Python Mistakes (50) Python Quiz (432) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (46) Udemy (17) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)