Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a list of dictionaries pass-by-value

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}]

like image 517
skvalen Avatar asked Jan 20 '26 11:01

skvalen


1 Answers

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
like image 125
NPE Avatar answered Jan 22 '26 23:01

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!