0

Suppose we have a list of integers L in python, and a function F which takes in an integer and returns a boolean. I have the following code:

for i in L:
   if F(i):
      do_whatever(i)

is there a way of doing this in one line in python, or rather, a more pythonic approach?

1 Answers1

1

Using the built-in python functions:

map(do_whatever, filter(F, L)) 
kezzos
  • 3,023
  • 3
  • 20
  • 37
  • Although that does create a new list (or is it an iterator) which may not be required. I would use map initially and then think about the performance hit later if it became an issue. And in python3 you def get an Iterator, so you have to consume it for it to do anything. – Tony Suffolk 66 Dec 16 '16 at 07:12