1

Given a list of N numbers, use a single list comprehension to produce a new list that only contains those values that are:

(a) even numbers, and
(b) from elements in the original list that had even indices

I am looking for a solution to the above problem. As suggested here there is an easy way to solve it but I would like to know if there is a way I can use a combination of map, lambda and filter on the "FULL" input list.

I am trying to do something like this but it doesn't work.

>>> map(lambda i,x : x%2==0 or (i+1)%2==0, range(0,len(l)-1),l)
[False, True, False, True, True]

Ideally I need to write something like (added "x if") but that doesnt work. Any suggestions?

map(lambda i,x : ***x if*** x%2==0 or (i+1)%2==0, range(0,len(l)-1),l)
5
  • 1
    Why do you want to solve it this way? map and filter aren't exactly deprecated, but a list comprehension is the logical solution here. Commented Oct 6, 2015 at 2:48
  • I am just trying to learn these features and want to know if there is a way to use IF with map and get a list of values back instead of a list of booleans... Do you know if there is a way? Commented Oct 6, 2015 at 2:54
  • Afaik, map doesn't allow if. You probably can use lambda with a conditional expression: a = b if c else d; that should solve the booleans problem. Commented Oct 6, 2015 at 2:57
  • You are filtering based on some criteria. map will not help you on this. It does not filter the input. It just applies a function to each element in the list. Commented Oct 6, 2015 at 3:03
  • Do the values have to satisfy both conditions a and b, or just at least one of them? Commented Oct 6, 2015 at 3:06

1 Answer 1

2

The problem specifically says "use a single list comprehension".

That having been said, you could do something like this:

>>> map(lambda x: x[1], filter(lambda x: x[0] % 2 == 0 and x[1] % 2 == 0, enumerate([0, 1, 5, 4, 4])))

enumerate will zip the indices with the digits themselves producing [(0, 0), (1, 1), (2, 5), (3, 4), (4, 4)]

filter with the given lambda will only be satisfied if both numbers in the tuple are even

map with the given lambda will discard the indices and keep the original numbers

leaving you with [0, 4] for this example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.