Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating object properties in list comprehension way

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

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

or with map function

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

Could it be achieved without for-looping with property setting?

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

like image 311
rook Avatar asked May 20 '13 13:05

rook


People also ask

How do you update an object in a list in Python?

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method.

How can list comprehension be faster?

List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.

Which type of compound statement does a list comprehension generally replace?

List comprehension is a complete substitute to for loops, lambda function as well as the functions map() , filter() and reduce() .

Is list comprehension faster than map Python?

Map function is faster than list comprehension when the formula is already defined as a function earlier. So, that map function is used without lambda expression.


1 Answers

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

There is a builtin which will do it (returning a list of None):

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

But please don't use it. Just use a loop. I doubt that you'll notice any difference in efficiency and a loop is so much more clear.

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

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

I find that most people want to use list-comprehensions because someone told them that they are "fast". That's correct, but only for creating a new list. Using a list comprehension for side-effects is unlikely to lead to any performance benefit and your code will suffer in terms of readability. Really, the most important reason to use a list comprehension instead of the equivalent loop with .append is because it is easier to read.

like image 143
mgilson Avatar answered Sep 29 '22 00:09

mgilson