-1

I have to print the even numbers by using only the lambda and map function. Not filter and any functions in python.

list(map(lambda x:x%2==0, range(20)))

OUTPUT:

[True, False, True, False, True, False, True, False, True, False, True, False, True, False, True, False, True, False, True, False]

Used the code like below

print(list(map(lambda x:x%2==0, range(20))))

I'm getting the boolean result but I need only even numbers. Is it possible by using a map function with lambda?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Rajeshkumar
  • 59
  • 1
  • 1
  • 9
  • Isn't range a function? – Evan Oct 02 '19 at 17:59
  • 1
    Possible duplicate of [list comprehension vs. lambda + filter](https://stackoverflow.com/questions/3013449/list-comprehension-vs-lambda-filter) – Patrick Haugh Oct 02 '19 at 17:59
  • 4
    `list(range(0, 20, 2))` would do the trick. Without even `map` or `lambda`. – norok2 Oct 02 '19 at 17:59
  • 2
    Sorry, assuming your instructor wants you to use only `map` and `lambda`, this isn't a duplicate. – Patrick Haugh Oct 02 '19 at 18:01
  • Also, you cannot write `map` in terms of `filter` or viceversa. If you are logically doing `filter` use that. Or the equivalent comprehension. With `lambda` you can do pretty much anything as that is just an unnamed function. But then the *"do not use any functions"* requirement becomes a bit iffy. Perhaps you want to add a bit more context to your question. – norok2 Oct 02 '19 at 18:07
  • 1
    `list(map(lambda x: x * 2, range(10)))` – Prasad Oct 02 '19 at 18:08
  • Is `[True, False] * 10` allowed? It doesn't use any of the banned functions because it doesn't use any functions at all. – kaya3 Feb 10 '20 at 08:54

3 Answers3

7

You can get the set of even integers by doubling every element of the set of integers. So all positive even integers less than n would be

n = 20
list(map(lambda n: n*2, range(n//2)))
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
2

You can use the filter method instead of map

list(filter(lambda x:x%2==0, range(1,20)))
Dhanush
  • 33
  • 4
0

@Patrick Haugh's answer is better, but you can also do it with a list comprehension to filter for you. My code is somewhat terrible because this isn't what map is for!

[x[1] for x in map(lambda x: (not x % 2, x), range(20)) if x[0]]

Please don't actually use this code for anything; use @norok2's comment instead. I wrote this for the challenge to myself and I wanted to see if it could be done, not because it's good.

list(range(0, 20, 2))
Jacinator
  • 1,413
  • 8
  • 11