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?

8
  • 2
    Yes, that is a generator. You'll have to iterate over it to get its contents. Calling list() on it will work. Commented Oct 7, 2020 at 23:05
  • 1
    It's an iterator. Generators are a specific kind of iterator. Commented Oct 7, 2020 at 23:06
  • When you want a list out map it's generally cleaner to use a list comprehension. Commented Oct 7, 2020 at 23:11
  • I am getting the output <function <lambda> at 0x7f7de21f31f0>. How are you getting <map object at 0x02937190> Commented Oct 7, 2020 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). Commented Oct 7, 2020 at 23:20

1 Answer 1

-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.

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

3 Comments

It returns the following error:Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'function' object is not iterable
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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.