Code Explanation:
๐น 1. Creating the List
nums = [1, 2, 3, 4, 5]
✅ Explanation:
A list named nums is created.
It contains:
[1, 2, 3, 4, 5]
๐น 2. Using filter()
result = filter(
✅ Explanation:
filter() is a built-in Python function.
It filters elements based on a condition.
Syntax:
filter(function, iterable)
function → returns True or False
iterable → list, tuple, etc.
๐น 3. Lambda Function
lambda x: x % 2 == 0
✅ Explanation:
This is an anonymous function.
Equivalent code:
def check(x):
return x % 2 == 0
Condition:
x % 2 == 0
Checks whether a number is even.
๐น 4. Passing the List
nums
✅ Explanation:
The lambda function will be applied to each element of:
[1, 2, 3, 4, 5]
๐น 5. Internal Working of filter()
Python checks every element one by one.
๐ For 1
1 % 2 == 0
Result:
False
❌ Rejected
๐ For 2
2 % 2 == 0
Result:
True
✅ Kept
๐ For 3
3 % 2 == 0
Result:
False
❌ Rejected
๐ For 4
4 % 2 == 0
Result:
True
✅ Kept
๐ For 5
5 % 2 == 0
Result:
False
❌ Rejected
๐น 6. Result After Filtering
Remaining values:
2
4
So internally:
filter object → [2, 4]
๐น 7. Converting to List
print(list(result))
✅ Explanation:
filter() returns a filter object (iterator).
list() converts it into a list.
Result:
[2, 4]
๐ฏ Final Output
[2, 4]
300 Days Python Coding Challenges with Explanation

0 Comments:
Post a Comment