-4
def extract_and_apply(l, p, f):
    result = []
    for x in l:
        if p(x):
            result.append(f(x))
    return result 

I'm new to python and I have to convert this function to a list comprehension, which I can't figure out. A little help would be really appreciated.

Ashok Kumar Jayaraman
  • 2,887
  • 2
  • 32
  • 40
  • Hey there, Theres plenty of examples of how to handle comprehension for many situations in there, along with many other questions already posted on SO if you search the topic *list comprehnsion* – vash_the_stampede Sep 25 '18 at 04:04

2 Answers2

1

List comprehensions use the same order as nested loops.

for a in blist:
     for c in dlist:
           if c in elist:
               result.append((a, c))

Can be written as:

result = [(a,c) for a in blist for c in dlist if c in elist]

Note: It's the same word order. When it gets confusing I just write out the nested loop and the delete the line breaks and colons.

Alex Weavers
  • 710
  • 3
  • 9
0
result = [f(x) for x in l if p(x)]

You can write if statements inside the list comprehension

Kazuya Hatta
  • 750
  • 1
  • 9
  • 19