Explanation:
Creating the List
nums = [-2, -1, 0, 1, 2]
A list named nums is created.
It contains negative numbers, zero, and positive numbers.
Using filter() with lambda
filter(lambda x: x, nums)
filter() keeps only those elements for which the function returns True.
lambda x: x means:
Return the value of x itself.
In Python:
0 is treated as False
Any non-zero number is treated as True
๐ So this line filters out 0 and keeps all other numbers.
Converting to a List
list(filter(lambda x: x, nums))
filter() returns a filter object, not a list.
list() converts the result into a readable list.
Printing the Result
print(list(filter(lambda x: x, nums)))
Prints the filtered list.
✅ Final Output
[-2, -1, 1, 2]

0 Comments:
Post a Comment