python - Pass list to function by value -


i want pass list function value. default, lists , other complex objects passed function reference. here desision:

def add_at_rank(ad, rank):     result_ = copy.copy(ad)     .. result_     return result_ 

can written shorter? in other words, wanna not change ad.

you can use [:], list containing lists(or other mutable objects) should go copy.deepcopy():

lis[:] equivalent list(lis) or copy.copy(lis), , returns shallow copy of list.

in [33]: def func(lis):     print id(lis)    ....:       in [34]: lis = [1,2,3]  in [35]: id(lis) out[35]: 158354604  in [36]: func(lis[:]) 158065836 

when use deepcopy():

in [41]: lis = [range(3), list('abc')]  in [42]: id(lis) out[42]: 158066124  in [44]: lis1=lis[:]  in [45]: id(lis1) out[45]: 158499244  # different lis, inner lists still same  in [46]: [id(x) x in lis1] = =[id(y) y in lis] out[46]: true  in [47]: lis2 = copy.deepcopy(lis)    in [48]: [id(x) x in lis2] == [id(y) y in lis]   out[48]: false 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -