Code Explanation:
๐น 1. Creating a List
nums = [1, 2, 3, 4]
✅ Explanation:
A list named nums is created.
Contents:
[1, 2, 3, 4]
Current state:
nums
↓
[1, 2, 3, 4]
๐น 2. Calling filter()
result = filter(
✅ Explanation:
filter() is a built-in Python function.
Its job:
Keep elements that satisfy a condition
Remove elements that don't
Syntax:
filter(function, iterable)
๐น 3. Lambda Function
lambda x: x % 2 == 0
✅ Explanation:
This is an anonymous function.
Equivalent to:
def check(x):
return x % 2 == 0
Rule:
If x is even → True
If x is odd → False
๐น 4. Understanding the Condition
x % 2 == 0
✅ Explanation:
% means modulus (remainder).
Examples:
2 % 2
Result:
0
3 % 2
Result:
1
Condition:
x % 2 == 0
means:
Is x divisible by 2?
If yes:
True
Otherwise:
False
๐น 5. First Iteration
Current value:
x = 1
Check:
1 % 2 == 0
Result:
False
So:
1 is discarded
๐น 6. Second Iteration
Current value:
x = 2
Check:
2 % 2 == 0
Result:
True
So:
2 is kept
๐น 7. Third Iteration
Current value:
x = 3
Check:
3 % 2 == 0
Result:
False
So:
3 is discarded
๐น 8. Fourth Iteration
Current value:
x = 4
Check:
4 % 2 == 0
Result:
True
So:
4 is kept
๐น 9. Result of Filter
After checking all elements:
Kept values:
2
4
Filtered object contains:
filter object
Not a list yet.
๐น 10. Converting to List
list(result)
✅ Explanation:
Converts filter object into a list.
Before:
<filter object at 0x...>
After:
[2, 4]
๐น 11. Printing Result
print(list(result))
prints:
[2, 4]
๐ฏ Final Output
[2, 4]

0 Comments:
Post a Comment