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.
mgilson
source share