0

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:

  1. Why do the side-effects happen?
  2. What's the idiomatic way of applying a function to a list of dicts without side-effects?
Andrei
  • 1
  • because dictionaries are mutable. If you want a list of brand new objects, then make a copy: `b = [some_fn(x.copy()) for x in a]`. Integers are not mutable, so the second time it works without making an explicit copy – Marat Apr 27 '22 at 20:13
  • This is not comparing the behavior of dict with list, but of dict with number. In the second function `x` is not a list. – trincot Apr 27 '22 at 20:13

0 Answers0