I have a bit of headache in a list of dicts.
def funk(x):
for i in x:
i['a'] += 1
print i
list1 = [{'a':1, 'b':2}, {'a':3, 'b':4}]
funk(list1)
print list1
this will output:
{'a': 2, 'b': 2}
{'a': 4, 'b': 4}
[{'a': 2, 'b': 2}, {'a': 4, 'b': 4}]
but I want to have this:
{'a': 2, 'b': 2}
{'a': 4, 'b': 4}
[{'a':1, 'b':2}, {'a':3, 'b':4}]
How do I make list1 stay untouched?
eg: [{'a':1, 'b':2}, {'a':3, 'b':4}]
funk() could make a copy of x and modify that copy instead of modifying the original x.
import copy
def funk(x):
x = copy.deepcopy(x)
for i in x:
i['a'] += 1
print i
list1 = [{'a':1, 'b':2}, {'a':3, 'b':4}]
funk(list1)
print list1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With