0

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.

Edward Falk
  • 9,991
  • 11
  • 77
  • 112
  • 1
    A `for in loop` is pythonic. There is no function like `foreach`. And 100,000 items in a list isnt that much. Depends on what your trying to do with each item. If you need true performance then using pure python isnt the way to go and would be better to use a library or a different language – TeddyBearSuicide Jan 19 '23 at 17:06
  • 1
    The closest you can get is to use a comprehension or `map`, along with the "walrus operator" to do the assignment, but those both return a new list, which you don't need. It's better to just use an explicit loop as you've done. – Tom Karzes Jan 19 '23 at 17:07
  • 1
    Well you could misuse `map` for this purpose but you can't write `lambda obj: obj.count=0` with lambda functions. The assignment isn't allowed there. – Abdul Aziz Barkat Jan 19 '23 at 17:20

1 Answers1

1

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.

JustLearning
  • 1,435
  • 1
  • 1
  • 9