user58925
user58925

Reputation: 1633

Python Map Lambda Memory

I have a list of objects, and I'd like to go through each object and change an attributed. Is there a difference in memory usage between (1) map lambda and (2) going through the list objects one by one.

Here is a simple example code

class F(object):
    def __init__(self):
        self.ID = 0

    def set_ID(self):
        self.ID = 1

number = 1000000
list_objects = [F() for i in xrange(n)]

There are two ways of using set_ID:

One way

map(lambda x: x.set_ID(), list_objects)

Another way

for obj in list_objects:
    obj.set_ID()

Upvotes: 0

Views: 341

Answers (1)

shizhz
shizhz

Reputation: 12501

I think the second way is better, map is used to apply a function to every item of an iterable and return a list of the results, so:

map(lambda x: x.set_ID(), list_objects)

will actually generate a list of 1000000 None, since you did not assign it to a variable, it will be discarded immediately and be garbage collected, since all item in this list is None, it will not eat too much memory. The state of your items in list_objects are changed because of the side effect of your lambda, I don't think this is the appropriate way to use map.

The second second method has nothing extra object created during the whole process. By the way, it could just be:

for obj in list_objects:
    obj.set_ID()

Upvotes: 1

Related Questions