1

I'm new to python lambda functions. So this question maybe a dummy one. I have the following sample code in python:

halve_evens_only = lambda nums: map(lambda i: i/2, filter(lambda i: not i%2, nums))

by calling this function like halve_evens_only([2,5,7,89,36]) I got the following output:

<map object at 0x02937190>

Is that a generator? How can I get the value ( I mean a list ) as an output of this function?

ng-hobby
  • 2,077
  • 2
  • 13
  • 26
  • 2
    Yes, that is a generator. You'll have to iterate over it to get its contents. Calling `list()` on it will work. – MattDMo Oct 07 '20 at 23:05
  • 1
    It's an *iterator*. Generators are a specific kind of iterator. – user2357112 Oct 07 '20 at 23:06
  • When you want a list out `map` it's generally cleaner to use a list comprehension. – Paul Rooney Oct 07 '20 at 23:11
  • I am getting the output ` at 0x7f7de21f31f0>`. How are you getting `` – anantdark Oct 07 '20 at 23:15
  • @PaulRooney: Especially in this case, where they're also using `filter`, and a listcomp could combine both operations into one. What they wrote could simplify to (and make an actual `list` in the process) `[i / 2 for i in nums if not i % 2]` (or `i // 2` to avoid conversion to `float`, which seems like the right idea given the division will be lossless). – ShadowRanger Oct 07 '20 at 23:20
  • @ShadowRanger that's exactly what I was about to suggest. – Paul Rooney Oct 07 '20 at 23:21
  • This is one of the contentious differences between Python 2 and Python 3. In Python2, `map` returns a list. In Python3, it returns an iterator, and as others have pointed out, you need to use `list(map(.....))` to get what you want. Check if your the text you're using to learn Python from is for Python2 or Python3. – Frank Yellin Oct 07 '20 at 23:25
  • @user2357112supportsMonica yes, that's what I meant. It was late, I was tired... – MattDMo Oct 08 '20 at 18:18

1 Answers1

-1

As you know Python is an object-oriented language. The output from lambda is stored as an object at that particular memory location. To print the output, you need to specify a datatype.

Let's say you specify list(). Then the output generated by the lambda function will be put in a list and presented at the output.

You can also specify any other datatype depending on the operation performed.

anantdark
  • 387
  • 1
  • 2
  • 12
  • It returns the following error:Traceback (most recent call last): File "", line 1, in TypeError: 'function' object is not iterable – ng-hobby Oct 07 '20 at 23:10
  • I don't think this will work. You are passing a lambda to `list`. I think what you want to do is pass the result of calling the lambda to `list`. – Paul Rooney Oct 07 '20 at 23:10
  • 2
    It's not that "you need to specify a datatype". The object already has a type. You're not specifying one. `list(...)` *calls* `list`, and `list` iterates over its argument and adds the retrieved items to a new list. – user2357112 Oct 07 '20 at 23:12