sam
sam

Reputation: 19164

Lambda functions are better or iterations?

Iterations is better or lambda functions are better in respect with time processing or memory usage and other things?

for example :

x = [10, 20, 30]

for y in x:
    if y>10 or y<20:
        print y

this is better or lambda function? I want the answer with respect to the time processing, memory usage or any other comparisons.

Upvotes: 2

Views: 2550

Answers (3)

georg
georg

Reputation: 214949

I find the list comprehension notation much easier to read than the functional notation, especially as the complexity of the expression to be mapped increases. In addition, the list comprehension executes much faster than the solution using map and lambda. This is because calling a lambda function creates a new stack frame while the expression in the list comprehension is evaluated without creating a new stack frame. >> http://python-history.blogspot.com/2010/06/from-list-comprehensions-to-generator.html

In other words, whether you have a choice between a lambda and a loop/comprehension/generator, use the latter. I guess the most pythonic way to write your example would be something like

 print [y for y in x if y < 20]

Upvotes: 1

aquavitae
aquavitae

Reputation: 19114

Iterators and lambdas are two completely different things. A lambda is a simple inline function and an iterator is an object which returns successive objects. There are two major problems with your example: You are testing x instead of y and all values in x will pass for y>10 or y<20. So, correcting those, your example could be written using an iterator and a lambda like this:

for value in filter(lamdba y: y < 10 or y > 20, x):
    print(value)

There are several ways you could do this, but in terms of performance it depends on what data you're processing, how you're processing it and how much of it you're processing. See http://wiki.python.org/moin/PythonSpeed/PerformanceTips for a useful guide.

Upvotes: 5

ThiefMaster
ThiefMaster

Reputation: 318458

For your case the classic loop is obviously better since you don't want to create a new list or generator.

Not creating such an object makes it more memory-efficient and not calling a function for each element makes it more performant.

Upvotes: 3

Related Questions