0

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()
1
  • yes obj = list_objects[i] Commented Apr 15, 2017 at 1:07

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.