Sunday, 19 July 2026

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

 


 Code Explanation:

๐Ÿ”น Step 1: Import cached_property
from functools import cached_property

cached_property is a modern Python feature.

It works like:

@property

but with one important difference:

The value is calculated only once
and then stored (cached).

๐Ÿ”น Step 2: Create Class
class A:

A new class named A is created.

๐Ÿ”น Step 3: Define Cached Property
@cached_property
def x(self):
    return []

This creates a property named:

x

When accessed for the first time:

a.x

Python executes:

return []

and stores the result.

๐Ÿ”น Step 4: Create Object
a = A()

Object created:

a

At this moment:

x has NOT been executed yet

because cached properties are lazy.

๐Ÿ”น Step 5: Access a.x
a.x.append(1)

Before .append() can run, Python evaluates:

a.x

Since this is the first access:

Python executes:

def x(self):
    return []

Result:

[]

This list is now cached internally.

Memory:

a.x ──► []

๐Ÿ”น Step 6: Execute Append

Now Python runs:

[].append(1)

List becomes:

[1]

Since the cached object itself was modified:

Memory becomes:

a.x ──► [1]

๐Ÿ”น Step 7: Print a.x
print(a.x)

Python checks:

Has x already been computed?

✅ Yes

So it does NOT execute:

return []

again.

Instead it returns the cached object:

[1]

๐Ÿ”น Step 8: Print Result
print([1])

Output:

[1]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (313) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) Books (287) Bootcamp (12) C (78) C# (12) C++ (83) cloud (1) Course (87) Coursera (300) Cybersecurity (33) data (9) Data Analysis (40) Data Analytics (28) data management (16) Data Science (399) Data Strucures (23) Deep Learning (201) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (24) Finance (11) flask (4) flutter (1) FPL (17) Generative AI (76) Git (12) Google (53) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (354) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (15) PHP (20) Projects (34) Python (1405) Python Coding Challenge (1202) Python Mathematics (5) Python Mistakes (51) Python Quiz (575) Python Tips (27) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (52) Udemy (18) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)