Code Explanation:
๐น 1. Creating a List
nums = [1, 2, 3, 4, 5]
✅ Explanation:
A list named nums is created.
Contents:
[1, 2, 3, 4, 5]
Current state:
nums
↓
[1, 2, 3, 4, 5]
๐น 2. Calling filter()
filter(lambda x: x % 2 == 0, nums)
✅ Explanation:
The filter() function checks every element of the list and keeps only those elements for which the condition returns True.
Syntax:
filter(function, iterable)
Here:
lambda x: x % 2 == 0
means:
Keep only even numbers.
๐น 3. Understanding the Lambda Function
lambda x: x % 2 == 0
✅ Explanation:
This lambda function checks whether a number is divisible by 2.
Equivalent code:
def check(x):
return x % 2 == 0
Examples:
1 % 2 = 1 → False ❌
2 % 2 = 0 → True ✅
3 % 2 = 1 → False ❌
4 % 2 = 0 → True ✅
5 % 2 = 1 → False ❌
๐น 4. Result of filter()
Python checks every element one by one.
Number Condition Action
1 False Remove ❌
2 True Keep ✅
3 False Remove ❌
4 True Keep ✅
5 False Remove ❌
After filtering:
2
4
The filter object contains:
2, 4
๐น 5. Calling map()
map(
lambda x: x * 10,
filter(...)
)
✅ Explanation:
Now map() receives the filtered values:
2
4
Its job is to apply a function to every element.
Syntax:
map(function, iterable)
๐น 6. Understanding the Second Lambda
lambda x: x * 10
✅ Explanation:
This lambda multiplies every value by 10.
Equivalent function:
def multiply(x):
return x * 10
๐น 7. First Iteration of map()
Current value:
x = 2
Calculation:
2 * 10
Result:
20
๐น 8. Second Iteration of map()
Current value:
x = 4
Calculation:
4 * 10
Result:
40
๐น 9. Result of map()
Generated values:
20
40
Internally:
map object
Not a list yet.
๐น 10. Converting to List
list(result)
✅ Explanation:
The map object is converted into a normal list.
Result:
[20, 40]
๐น 11. Printing the Output
print(list(result))
✅ Explanation:
Prints:
[20, 40]
๐ฏ Final Output
[20, 40]

0 Comments:
Post a Comment