Updating object properties in list comprehension order

Is it possible, in Python, to update a list of objects in a list comprehension or similar way? For example, I would like to set the property of all objects in a list:

result = [ object.name = "blah" for object in objects] 

or with map function

 result = map(object.name = "blah", objects) 

Can this be achieved without looping with setting the property?

(Note: all of the above examples are intentionally wrong and are provided only to express an idea)

+8
python list-comprehension
source share
1 answer

Ultimately, an assignment is a Statement, not an Expression, so it cannot be used in a lambda expression or list comprehension. You need a regular function to accomplish what you are trying.

There is a built-in file that will do this (returns a None list):

 [setattr(obj,'name','blah') for obj in objects] 

But please do not use it. Just use a loop. I doubt that you will notice any difference in efficiency, and the cycle will become much clearer.

If you really need a 1-liner (although I don’t understand why):

 for obj in objects: obj.name = "blah" 

I find that most people want to use lists because someone told them they are "fast." This is correct, but only to create a new list. Using list comprehension for side effects is unlikely to bring any performance benefits, and your code will suffer in terms of readability. In fact, the most important reason for using list comprehension instead of an equivalent loop with .append is that it is easier to read.

+20
source share

All Articles