Explanation:
1. Creating the List
nums = [0, 1, 2, 3, 4, 5]
This line creates a list named nums.
It contains integers from 0 to 5.
The list has both falsey (0) and truthy (1–5) values in Python.
2. Using filter() with bool
result = list(filter(bool, nums))
a) filter(bool, nums)
filter() checks each element in nums.
The bool function is applied to every element.
In Python:
bool(0) → False
bool(1), bool(2), … → True
b) What gets filtered?
Elements that evaluate to False are removed.
Elements that evaluate to True are kept.
So:
0 is removed
1, 2, 3, 4, 5 are kept
c) list(...)
filter() returns a filter object.
list() converts it into a list.
3. Printing the Result
print(result)
This line prints the final filtered list to the screen.
4. Final Output
[1, 2, 3, 4, 5]
Only truthy values remain.
0 is excluded because it is considered False in Python.

0 Comments:
Post a Comment