Home > other >  Apply function to each element of a list in place
Apply function to each element of a list in place

Time:01-20

Similar question to Apply function to each element of a list, however the answers to that question (list comprehension or map()) really return a new list to replace the old one.

I want to do something like this:

for obj in myList:
    obj.count = 0

Obviously I could (and currently do) process the list exactly this way, but I was wondering if there were a construct such as

foreach(lambda obj: obj.count=0, myList)

Obviously I only care about this if the more "pythonic" way is more efficient. My list can have over 100,000 elements, so I want this to be quick.

CodePudding user response:

Note that your question is not about replacing elements of a list in-place, but rather mutating an attribute of each element, without replacing the latter. Your attempt in terms of a for loop is the way to go.

  • Related