Is there an in-place equivalent to 'map' in python?

Herms picture Herms · Nov 10, 2010 · Viewed 11.2k times · Source

I have a list of strings that I need to sanitize. I have a method for sanitizing them, so I could just do:

new_list = map(Sanitize, old_list)

but I don't need to keep the old list around. This got me wondering if there's an in-place equivalent to map. Easy enough to write a for loop for it (or a custom in-place map method), but is there anything built in?

Answer

Glenn Maynard picture Glenn Maynard · Nov 10, 2010

The answer is simply: no.

Questions of the form "does XXX exist" never tend to get answered directly when the answer is no, so I figured I'd put it out there.

Most itertools helpers and builtins operate on generic iterators. map, filter, list comprehensions, for--they all work on iterators, not modifying the original container (if any).

Why aren't there any mutating functions in this category? Because there's no generic, universal way to assign values to containers with respect to their keys and values. For example, basic dict iterators (for x in {}) iterate over the keys, and assigning to a dict uses the result of the dict as the parameter to []. Lists, on the other hand, iterate over the values, and assignment uses the implicit index. The underlying consistency isn't there to provide generic functions like this, so there's nothing like this in itertools or in the builtins.

They could provide it as a methods of list and dict, but presently they don't. You'll just need to roll your own.