I have a list of dictionaries, and I would like to generate a new list whose elements are some function applied to the original list's elements, without making any changes to the original list. If I simply apply the function, it affects the original list:
def some_fn(x):
x["a"] = x["a"] + 1
return x
a = [{"a":1}, {"a":2}, {"a":3}]
b = [some_fn(x) for x in a]
a, b
>>> ([{'a': 2}, {'a': 3}, {'a': 4}], [{'a': 2}, {'a': 3}, {'a': 4}])
If I apply a similar function to a list of, say, ints, it doesn't have side-effects:
def some_fn(x):
x += 1
return x
a = [1, 2, 3]
b = [some_fn(x) for x in a]
a, b
>>> ([1, 2, 3], [2, 3, 4])
Questions:
- Why do the side-effects happen?
- What's the idiomatic way of applying a function to a list of dicts without side-effects?