1.

Write a python program to filter list elements between 1 to 20 (both inclusive) which are even numbers?

Answer»

This can be done in many WAYS. But the more pythonic WAY of doing this is to use filter and lambda.

filter() method takes a function and a sequence. The function should return true or false. It runs a function on each element in the sequence and returns an iterator for the elements for which the function returns true.

We can pass a normal function to filter but the more pythonic way of doing it is to pass a lambda.

nums = list(range(1, 21)) # Include 20filtered_elements = list(filter(lambda x: (x%2 == 0), nums)) # CONVERT iterator to list


Discussion

No Comment Found