Showing posts with label Python Coding Challenge. Show all posts
Showing posts with label Python Coding Challenge. Show all posts

Monday, 18 May 2026

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

 


Code Explanation:

๐Ÿ”น 1. First List Creation
a = [1,2,3]
✅ Explanation:
A list a is created.
Elements are:
[1, 2, 3]

๐Ÿ”น 2. Second List Creation
b = [4,5,6]
✅ Explanation:
Another list b is created.
Elements are:
[4, 5, 6]

๐Ÿ”น 3. Using map()
result = map(lambda x,y: x+y, a, b)
✅ Explanation:

map() applies a function to elements of iterables.

๐Ÿ”น 4. Lambda Function
lambda x,y: x+y
✅ Explanation:
Anonymous function (lambda)
Takes:
x, y
Returns:
x + y

๐Ÿ”น 5. Pairwise Processing

map() takes values from both lists together.

๐Ÿ” Internally:
x y x+y
1 4 5
2 5 7
3 6 9

๐Ÿ”น 6. map() Returns Iterator
✅ Explanation:

map() does NOT directly return list.

It returns:

map object (iterator)

which generates values lazily.

๐Ÿ”น 7. Converting to List
print(list(result))
✅ Explanation:
list() consumes iterator
Collects all generated values into list
Final list:
[5, 7, 9]

๐ŸŽฏ Final Output
[5, 7, 9]

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

 


Code Explanation:

๐Ÿ”น 1. Generator Function Definition
def gen():
✅ Explanation:
A generator function gen() is created.
Since it uses yield, it becomes a generator.

๐Ÿ”น 2. Receiving Value with yield
x = yield
✅ Explanation:

This is a special use of yield.

๐Ÿ” What it does:
Pauses generator execution
Waits to RECEIVE a value using:
send(value)

The received value gets stored in:

x

๐Ÿ”น 3. Second yield
yield x * 2
✅ Explanation:
Multiplies received value by 2
Returns result using yield

๐Ÿ”น 4. Creating Generator Object
g = gen()
✅ Explanation:
Calling gen() does NOT run function immediately.
It creates a generator object g.

๐Ÿ”น 5. Starting Generator
next(g)
✅ Explanation:

Before using:

send(value)

generator must first reach the first yield.

๐Ÿ” What happens internally:

Execution starts:

x = yield

Generator pauses here waiting for value.

⚠️ Important:

At this moment:

x → not assigned yet

Generator is now ready to receive data.

๐Ÿ”น 6. Sending Value into Generator
g.send(5)
✅ Explanation:
Sends value 5 into paused generator.
That value becomes:
x = 5

๐Ÿ”น 7. Execution Resumes

After receiving value:

yield x * 2
Calculation:
5 * 2 = 10

Generator yields:

10

๐Ÿ”น 8. Printing Result
print(g.send(5))
✅ Output:
10

๐ŸŽฏ Final Output
10

Sunday, 17 May 2026

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

 



Code Explanation:

๐Ÿ”น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
Inside this class, a method gen() is defined.

๐Ÿ”น 2. Generator Method Definition
def gen(self):
✅ Explanation:
gen is an instance method.
self refers to the current object.
⚠️ Important:

Because this method contains yield,
it becomes a generator method.

๐Ÿ”น 3. for Loop Inside Generator
for i in range(3):
✅ Explanation:
Loop runs 3 times:
0, 1, 2

๐Ÿ”น 4. yield Statement
yield i
✅ Explanation:
yield returns one value at a time.
After returning value, function pauses.
State is saved for next iteration.

๐Ÿ”น 5. Object Creation
obj = Test()
✅ Explanation:
Creates object obj of class Test.

๐Ÿ”น 6. Calling Generator Method
obj.gen()
✅ Explanation:
Method does NOT execute immediately.
It returns a generator object.

๐Ÿ”น 7. for Loop Iteration
for x in obj.gen():
✅ Explanation:
Python internally calls:
next(generator)

again and again.

๐Ÿ”น 8. First Iteration
๐Ÿ” Execution:
i = 0
yield 0
✔️ Printed:
0

Function pauses here.

๐Ÿ”น 9. Second Iteration
๐Ÿ” Execution resumes:
i = 1
yield 1
✔️ Printed:
1

Function pauses again.

๐Ÿ”น 10. Third Iteration
๐Ÿ” Execution resumes:
i = 2
yield 2
✔️ Printed:
2
๐Ÿ”น 11. Generator Ends
✅ Explanation:
Loop finishes after i = 2
Generator has no more values
Python raises internal:
StopIteration

The for loop automatically handles it and stops.

๐ŸŽฏ Final Output
0
1
2

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

 


Code Explanation:

๐Ÿ”น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
Inside this class:
A decorator function deco is defined
A method show is defined

๐Ÿ”น 2. Decorator Function Definition
def deco(func):
✅ Explanation:
deco is a decorator function.
It takes another function (func) as argument.
๐Ÿ” In this code:

func will be:

show()

๐Ÿ”น 3. Wrapper Function Inside Decorator
def wrapper(self):
✅ Explanation:
wrapper is a new function created inside decorator.
This function will replace original show() method.
self refers to current object (obj).

๐Ÿ”น 4. Modified Return Statement
return "Hello " + func(self)
✅ Explanation:
Calls original function:
func(self)
๐Ÿ” Original show() returns:
"World"

So final result becomes:

"Hello World"

๐Ÿ”น 5. Returning Wrapper
return wrapper
✅ Explanation:
Decorator returns wrapper.
So original function is replaced by wrapper function.

๐Ÿ”น 6. Applying Decorator
@deco
✅ Explanation:

This line means:

show = deco(show)
๐Ÿ” What happens:
Original show() is passed into deco
deco returns wrapper
show now points to wrapper

๐Ÿ”น 7. Original Method
def show(self):
    return "World"
✅ Explanation:
Original method simply returns:
"World"

But because of decorator,
this method is wrapped inside wrapper.

๐Ÿ”น 8. Object Creation
obj = Test()
✅ Explanation:
Creates object obj of class Test.

๐Ÿ”น 9. Calling Method
print(obj.show())
๐Ÿ” What happens internally:

Because of decorator:

obj.show()

actually becomes:

wrapper(obj)

๐Ÿ”น 10. Execution Inside Wrapper
Step 1:
func(self)

calls original:

show(obj)

returns:

"World"
Step 2:

Wrapper adds:

"Hello " + "World"

Result:

"Hello World"

๐ŸŽฏ Final Output
Hello World

Saturday, 16 May 2026

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

 


Code Explanation:

1. Generator Function Definition
def gen():
✅ Explanation:
A function gen() is created.
Since it contains yield, it becomes a generator function.
⚠️ Important:
Generator functions do NOT run immediately.
They return a generator object.


๐Ÿ”น 2. First Print Statement
print("A")
✅ Explanation:
When execution starts, "A" will be printed first.

๐Ÿ”น 3. First yield
yield 1
✅ Explanation:
yield returns a value (1)
Then pauses the function
Function state is remembered

๐Ÿ”น 4. Second Print Statement
print("B")
✅ Explanation:
This line runs only when generator resumes after first pause.

๐Ÿ”น 5. Second yield
yield 2
✅ Explanation:
Returns 2
Again pauses the generator

๐Ÿ”น 6. Creating Generator Object
g = gen()
✅ Explanation:
gen() is called
But function body does NOT execute yet
A generator object g is created

๐Ÿ”น 7. First next() Call
print(next(g))
๐Ÿ” What happens internally:

Generator starts execution from beginning.

Step-by-step:

Executes:

print("A")

Output:

A

Reaches:

yield 1

Returns:

1
Generator pauses here
✔️ Output so far:
A
1

๐Ÿ”น 8. Second next() Call
print(next(g))
๐Ÿ” What happens internally:

Generator resumes from where it paused.

Step-by-step:

Executes:

print("B")

Output:

B

Reaches:

yield 2

Returns:

2
Generator pauses again

๐ŸŽฏ Final Output
A
1
B
2

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

 


Code Explanation:

๐Ÿ”น 1. Function Definition
def func():
✅ Explanation:
A function named func is created.
It contains:
try block
except block
finally block

๐Ÿ”น 2. try Block
try:
    print(10 / 0)
✅ Explanation:
Python tries to execute:
10 / 0
⚠️ Problem:

Division by zero is not allowed.

So Python raises:

ZeroDivisionError

๐Ÿ”น 3. Exception Occurs
ZeroDivisionError
✅ Explanation:
Since an error occurs inside try,
Python immediately stops the remaining try code
It searches for a matching except

๐Ÿ”น 4. except Block
except ZeroDivisionError:
    print("ERROR")
✅ Explanation:
This block catches only:
ZeroDivisionError
✔️ So it runs:
print("ERROR")
Output:
ERROR

๐Ÿ”น 5. finally Block
finally:
    print("DONE")
✅ Explanation:
finally always executes:
Error occurred ✅
No error ✅
Return statement ✅
✔️ So it prints:
DONE

๐Ÿ”น 6. Function Call
func()
✅ Execution Flow:
try → error occurs
       ↓
except runs
       ↓
finally runs

๐ŸŽฏ Final Output
ERROR
DONE

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

 


Code Explanation:

๐Ÿ”น 1. Function Definition
def func():
✅ Explanation:
A function func is defined.
It contains try, except, and finally blocks.

๐Ÿ”น 2. try Block
try:
    print("A")
    return 1
✅ Explanation:
First, "A" is printed.
Then return 1 is executed.
⚠️ Important:
Even though return is reached, Python does NOT immediately exit
It will still execute the finally block

๐Ÿ”น 3. except Block
except:
    print("B")
✅ Explanation:
Runs only if an exception occurs in try
In this case:
No error happens
So this block is skipped

๐Ÿ”น 4. finally Block
finally:
    print("C")
✅ Explanation:
This block always executes, no matter what:
Return
Exception
Normal execution

๐Ÿ‘‰ So "C" is printed even after return

๐Ÿ”น 5. Calling the Function
print(func())
๐Ÿ” Step-by-step execution:

print("A") → prints:

A
return 1 is prepared (but paused)

finally runs → prints:

C
Function returns 1

Outer print() prints:

1

๐ŸŽฏ Final Output
A
C
1

Wednesday, 6 May 2026

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

 


 Code Explanation:

๐Ÿ”น 1. Outer Function Definition
def outer(x):
✅ Explanation:
A function outer is defined.
It takes one argument: x.
This function will return another function.

๐Ÿ”น 2. Inner Function Definition
def inner(y):
✅ Explanation:
Inside outer, another function inner is defined.
It takes parameter y.

๐Ÿ”น 3. Using Outer Variable Inside Inner
return x + y
✅ Explanation:
inner uses:
y → its own parameter
x → from outer function

๐Ÿ‘‰ This is called a closure:

Inner function remembers the value of x even after outer finishes

๐Ÿ”น 4. Returning Inner Function
return inner
✅ Explanation:
outer does NOT return a value directly
It returns the function inner itself

๐Ÿ”น 5. Calling Outer Function
f = outer(5)
๐Ÿ” What happens:
outer(5) is executed
x = 5
Returns inner function

๐Ÿ‘‰ Now:

f → inner (with x = 5 stored)

๐Ÿ”น 6. Calling Returned Function
print(f(3))
๐Ÿ” What happens:
Calls:
inner(3)

Inside inner:

x = 5 (remembered from closure)
y = 3
Calculation:
5 + 3 = 8
๐ŸŽฏ Final Output
8

Monday, 4 May 2026

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

 


Code Explanation:

๐Ÿ”น 1. Initializing the List
funcs = []
An empty list funcs is created
This list will store functions

๐Ÿ”น 2. Starting the Loop
for i in range(3):

Loop runs 3 times with values:

i = 0, 1, 2

๐Ÿ”น 3. Defining the Function Inside Loop
def f():
    return i
A function f is defined in each iteration
⚠️ Important: The function does not store the current value of i immediately
Instead, it refers to i (late binding)

๐Ÿ‘‰ This means:

All functions will look up i when they are called, not when they are created

๐Ÿ”น 4. Appending Function to List
funcs.append(f)
The function f is added to the list
After loop ends, funcs contains 3 functions

๐Ÿ”น 5. After Loop Ends
Final value of i is:
i = 2
All functions refer to this same i

๐Ÿ”น 6. Calling the Functions
print([f() for f in funcs])
Each function is called one by one
Each function returns the current value of i, which is 2

๐Ÿ”น ✅ Final Output
[2, 2, 2]

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

 


Code Explanation:

๐Ÿ”น 1. Metaclass Definition
class Meta(type):
    def __new__(cls, name, bases, dct):
        dct['x'] = 100
        return super().__new__(cls, name, bases, dct)
Meta is a metaclass (inherits from type)
__new__ runs when a class is being created, not an object
It receives the class attributes in dct

It modifies the class dictionary by setting:

x = 100

๐Ÿ”น 2. Class Creation (A)
class A(metaclass=Meta):
    x = 10
Python sends this class definition to the metaclass

Internally:

Meta.__new__(Meta, 'A', (), {'x': 10})

The metaclass changes:

{'x': 10} → {'x': 100}

๐Ÿ”น 3. Final Class Structure

After metaclass processing, class A becomes:

class A:
    x = 100
The original x = 10 is overwritten

๐Ÿ”น 4. Object Creation
obj = A()
Creates an instance of class A
obj itself has no x attribute

๐Ÿ”น 5. Attribute Lookup
print(obj.x)
Python checks:
obj → not found
class A → finds x = 100

๐Ÿ”น ✅ Final Output
100

Tuesday, 28 April 2026

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

 


Code Explanation:

๐Ÿ”น 1. Importing Module
import copy
✅ Explanation:
Imports Python’s built-in copy module.
This module provides:
copy.copy() → shallow copy
copy.deepcopy() → deep copy

๐Ÿ”น 2. Creating Nested List
a = [[1,2],[3,4]]
✅ Explanation:
a is a list of lists (nested structure).
Memory structure:
Outer list contains two inner lists
a → [ [1,2], [3,4] ]

๐Ÿ”น 3. Deep Copy
b = copy.deepcopy(a)
✅ Explanation:
Creates a completely independent copy of a.
Both:
Outer list
Inner lists
are copied separately.
๐Ÿ” Important:
b ≠ a
b[0] ≠ a[0]

✔️ No shared references

๐Ÿ”น 4. Modifying Copied List
b[0][0] = 100
✅ Explanation:
Changes first element of first inner list in b
So:
b → [ [100,2], [3,4] ]

๐Ÿ”น 5. Printing Original List
print(a)
✅ Explanation:
Since a and b are completely independent,
Changes in b do NOT affect a

๐ŸŽฏ Final Output
[[1, 2], [3, 4]]

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

 


 Code Explanation:

๐Ÿ”น 1. Function Definition
def gen():
✅ Explanation:
A function gen is defined.
Because it uses yield, it becomes a generator function (not a normal function).


๐Ÿ”น 2. First yield
yield 1
✅ Explanation:
yield produces a value without ending the function.
It pauses execution and remembers its state.

๐Ÿ”น 3. Second yield
yield 2
✅ Explanation:
When resumed, the function continues from where it stopped.
Now it yields 2.

๐Ÿ”น 4. Third yield
yield 3
✅ Explanation:
On next resume, it yields 3.
After this, the generator is exhausted.

๐Ÿ”น 5. Creating Generator Object
g = gen()
✅ Explanation:
Calling gen() does NOT execute the function immediately.
It returns a generator object.
Execution starts only when next() is called.

๐Ÿ”น 6. First next() Call
print(next(g))
๐Ÿ” What happens:
Starts execution of gen()
Runs until first yield
✔️ Output:
1

๐Ÿ”น 7. Second next() Call
print(next(g))
๐Ÿ” What happens:
Resumes from previous pause
Continues to second yield

✔️ Output:
2

๐ŸŽฏ Final Output
1
2

Tuesday, 21 April 2026

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

 


Code Explanataion:

๐Ÿงฉ 1. Decorator Function Definition
def decorator(func):
Defines a function named decorator.
It takes another function (func) as an argument.
This is the core idea of decorators: functions that modify other functions.

๐Ÿ” 2. Wrapper Function Inside Decorator
    def wrapper():
A nested function wrapper is defined.
This function will replace/extend the behavior of func.

✖️ 3. Modify Original Function Output
        return func() * 2
Calls the original function func().
Multiplies its result by 2.
Returns the modified value.

๐Ÿ”™ 4. Return Wrapper Function
    return wrapper
The decorator returns the wrapper function.
This means the original function will be replaced by wrapper.

๐ŸŽฏ 5. Applying the Decorator
@decorator

This is syntactic sugar for:

say = decorator(say)
It passes say into decorator and replaces it with wrapper.

๐Ÿ“ฆ 6. Original Function Definition
def say():
    return 5
A simple function that returns 5.
But due to the decorator, this function will not run directly.

๐Ÿ”„ 7. What Actually Happens Internally

After decoration:

say = decorator(say)
Now say actually refers to wrapper.
When you call say(), it calls wrapper().

๐Ÿ–จ️ 8. Function Call and Output
print(say())
Execution Flow:
say() → actually calls wrapper()
wrapper() → calls original func() → returns 5
5 * 2 = 10

✅ Final Output
10

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

 


Code Explanation:

๐Ÿงฉ 1. Function Definition: outer
def outer():
This defines a function named outer.
It acts as an enclosing (parent) function.

๐Ÿ“ฆ 2. Variable Initialization
    x = 10
A local variable x is created inside outer.
Initial value of x is 10.

๐Ÿ” 3. Inner Function Definition
    def inner():
A nested function named inner is defined inside outer.
It has access to variables of outer (like x).

๐Ÿ”— 4. Using nonlocal
        nonlocal x
nonlocal means:
“Use the variable x from the nearest enclosing scope (outer function), not create a new one.”
Without nonlocal, modifying x would cause an error.

➕ 5. Modify the Variable
        x += 5
Adds 5 to the existing value of x.
Since x is nonlocal, it updates the outer function’s x.

๐Ÿ”™ 6. Return Updated Value
        return x
Returns the updated value of x.

๐Ÿ“ค 7. Return Inner Function
    return inner
The outer function returns the inner function itself, not its result.
This creates a closure (function + its environment).

๐ŸŽฏ 8. Create Function Instance
f = outer()
Calls outer(), which returns inner.
Now f becomes a reference to inner, with x = 10 preserved.

๐Ÿ–จ️ 9. Function Calls and Output
print(f(), f())
First Call: f()
x = 10
x += 5 → 15
Returns 15
Second Call: f()
x = 15 (value persists due to closure)
x += 5 → 20
Returns 20

✅ Final Output
15 20

Monday, 13 April 2026

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

 


Code Explanation:

๐Ÿ”น 1. Base Class Definition
class A: 
    pass
✅ Explanation:
A class A is created.
pass means the class has no attributes or methods (empty class).

๐Ÿ”น 2. Derived Class (Inheritance)
class B(A): 
    pass
✅ Explanation:
Class B is created and inherits from class A.
This means:
B gets all properties of A.
B IS-A A (important concept in OOP).

๐Ÿ”น 3. Object Creation
obj = B()
✅ Explanation:
An object obj of class B is created.
So:
obj belongs to class B
But also indirectly belongs to class A (because of inheritance)

๐Ÿ”น 4. isinstance() Check
isinstance(obj, A)
✅ Explanation:
Checks if obj is:
An instance of class A OR
Any subclass of A
๐Ÿ” In this case:
obj is instance of B
B inherits from A
So:
True

๐Ÿ”น 5. type() Comparison
type(obj) == A
✅ Explanation:
type(obj) returns the exact class of the object.
Here:
type(obj) → B
So comparison becomes:
B == A  → False

๐Ÿ”น 6. Final Print Statement
print(isinstance(obj, A), type(obj) == A)
✅ Output:
True False

๐ŸŽฏ Final Output
True False

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

 


Code Explanation:

๐Ÿ”น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
It will contain a variable and two methods.

๐Ÿ”น 2. Class Variable
x = 10
✅ Explanation:
x is a class variable.
Shared across all instances of the class.
Accessible via:
Test.x
cls.x (inside class methods)

๐Ÿ”น 3. Class Method (@classmethod)
@classmethod
def show(cls):
    return cls.x
✅ Explanation:
@classmethod decorator defines a method that works with the class, not instance.
cls refers to the class (Test).
๐Ÿ” What happens:
cls.x → accesses class variable x
Returns:
10

๐Ÿ”น 4. Static Method (@staticmethod)
@staticmethod
def display():
    return Test.x
✅ Explanation:
@staticmethod creates a method that:
Does NOT take self or cls
Works like a normal function inside the class
๐Ÿ” What happens:
Directly accesses:
Test.x
Returns:
10

๐Ÿ”น 5. Calling Methods
print(Test.show(), Test.display())

✅ Step-by-step:
➤ Test.show()
Calls class method
cls = Test
Returns:
10
➤ Test.display()
Calls static method
Returns:
10

๐ŸŽฏ Final Output
10 10

Book:  700 Days Python Coding Challenges with Explanation

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

 


Code Explanation:

๐Ÿ”น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
This class will define how its objects are represented as strings.

๐Ÿ”น 2. __str__ Method
def __str__(self):
    return "STR"
✅ Explanation:
__str__ is a magic method used for user-friendly string representation.
It is called when:
print(obj)
str(obj)

Here, it returns:

"STR"

๐Ÿ”น 3. __repr__ Method
def __repr__(self):
    return "REPR"
✅ Explanation:
__repr__ is another magic method used for:
Debugging
Developer-friendly representation
It is called when:
You type obj in interpreter
Or when __str__ is not defined

๐Ÿ”น 4. Creating Object
obj = Test()
✅ Explanation:
An object obj of class Test is created.
No constructor (__init__) is defined, so default is used.

๐Ÿ”น 5. Printing Object
print(obj)
✅ What happens internally:

Python follows this priority:

Call __str__()
If not available → call __repr__()
๐Ÿ” In this case:
__str__ exists → used
So:
obj.__str__()

returns:

"STR"

๐ŸŽฏ Final Output
STR

Friday, 10 April 2026

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

 


Code Explanation:

๐Ÿ”น 1. Class Definition
class Test:
    x = []
✅ Explanation:
A class named Test is created.
x = [] is a class variable (shared by all objects).
This means:
Only one list exists in memory.
All instances (a, b, etc.) will refer to the same list unless overridden.

๐Ÿ”น 2. Constructor (__init__ method)
def __init__(self, value):
    self.x.append(value)

✅ Explanation:
This method runs whenever an object is created.
self refers to the current object.
self.x.append(value):
Python first looks for x inside the instance.
Not found → it looks in the class.
Finds x (the shared list).
So, it appends the value to the same shared list.

๐Ÿ”น 3. Creating First Object
a = Test(1)
✅ What happens:
Object a is created.
__init__(1) runs.
self.x.append(1) → list becomes:
[1]

๐Ÿ”น 4. Creating Second Object
b = Test(2)
✅ What happens:
Object b is created.
__init__(2) runs.
Again, self.x refers to the same class list.
2 is appended → list becomes:
[1, 2]

๐Ÿ”น 5. Printing Values
print(a.x, b.x)
✅ Explanation:
Both a.x and b.x refer to the same list.
So output is:
[1, 2] [1, 2]

⚠️ Key Concept (Very Important)
๐Ÿ”ธ Class Variable vs Instance Variable
Type Defined Where Shared?
Class Variable Inside class ✅ Yes
Instance Variable Inside __init__ using self ❌ No
๐Ÿ”ฅ Why This Happens

Because:

x = []

is defined at class level, not inside __init__.

✅ How to Fix (If You Want Separate Lists)
class Test:
    def __init__(self, value):
        self.x = []      # instance variable
        self.x.append(value)

✔️ Output now:
[1] [2]

๐ŸŽฏ Final Answer
[1, 2] [1, 2]

Tuesday, 7 April 2026

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

 


Code Explanation:

1️⃣ Defining the Class
class A:

Explanation

A class A is created.
It will contain variables and methods.

2️⃣ Defining Class Variable
x = 10

Explanation

x is a class variable.
It belongs to the class, not individual objects.

3️⃣ Defining @classmethod
@classmethod
def f(cls):

Explanation

f is a class method.
It receives the class itself as cls.

4️⃣ Accessing Class Variable via cls
return cls.x

Explanation

Accesses class variable x using cls.
Works for inheritance too (dynamic reference).

5️⃣ Defining @staticmethod
@staticmethod
def g():

Explanation

g is a static method.
It does NOT receive self or cls.

6️⃣ Accessing Class Variable Directly
return A.x

Explanation

Directly accesses class A.
Not flexible for inheritance (hardcoded).

7️⃣ Calling Methods
print(A.f(), A.g())

Explanation

Calls both methods using class A.

๐Ÿ”„ Method Execution
๐Ÿ”น A.f()
cls = A
Returns:
A.x → 10
๐Ÿ”น A.g()
Directly returns:
A.x → 10

๐Ÿ“ค Final Output
10 10

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

 


Code Explanation:

1️⃣ Importing dataclass
from dataclasses import dataclass

Explanation

Imports the dataclass decorator.
It auto-generates methods like __init__, __repr__, etc.

2️⃣ Applying @dataclass
@dataclass

Explanation

Converts class A into a dataclass.
Automatically creates constructor like:
def __init__(self, x=[]):
    self.x = x

⚠️ Important: x=[] is evaluated once, not per object.

3️⃣ Defining Class
class A:

Explanation

Defines class A.

4️⃣ Defining Attribute with Default Value
x: list = []

Explanation ⚠️ CRITICAL

x is given a default value of an empty list.
This list is shared across all instances.

๐Ÿ‘‰ Only ONE list is created in memory.

5️⃣ Creating First Object
a1 = A()

Explanation

a1.x refers to the shared list.

6️⃣ Creating Second Object
a2 = A()

Explanation

a2.x refers to the same shared list.

๐Ÿ‘‰ So:

a1.x is a2.x → True

7️⃣ Modifying List from a1
a1.x.append(1)

Explanation

Adds 1 to the shared list.

๐Ÿ‘‰ Now shared list becomes:

[1]

8️⃣ Printing from a2
print(a2.x)

Explanation

Since a2.x points to the same list:
[1]

๐Ÿ“ค Final Output
[1]

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (264) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (30) Azure (10) BI (10) Books (262) Bootcamp (11) C (78) C# (12) C++ (83) Course (87) Coursera (300) Cybersecurity (31) data (6) Data Analysis (33) Data Analytics (22) data management (15) Data Science (360) Data Strucures (17) Deep Learning (167) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (73) Git (10) Google (51) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (42) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (302) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (14) PHP (20) Projects (34) pytho (1) Python (1350) Python Coding Challenge (1142) Python Mathematics (1) Python Mistakes (51) Python Quiz (513) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (49) Udemy (18) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)