Copy values from one list to another without altering the reference in python -


in python objects such lists passed reference. assignment = operator assigns reference. function:

def modify_list(a):     = [1,2,3,4] 

takes reference list , labels a, sets local variable a new reference; list passed calling scope not modified.

test = [] modify_list(test) print(test) 

prints []

however this:

def modify_list(a):     += [1,2,3,4]  test = [] modify_list(test) print(test) 

prints [1,2,3,4]

how can assign list passed reference contain values of list? looking functionally equivelant following, simpler:

def modify_list(a):     list_values = [1,2,3,4]     in range(min(len(a), len(list_values))):         a[i] = list_values[i]      in range(len(list_values), len(a)):         del a[i]      in range(len(a), len(list_values)):         += [list_values[i]] 

and yes, know not way <whatever want do>, asking out of curiosity not necessity.

you can slice assignment:

>>> def mod_list(a, new_a): ...    a[:]=new_a ...  >>> lia=[1,2,3] >>> new=[3,4,5,6,7] >>> mod_list(lia, new) >>> lia [3, 4, 5, 6, 7] 

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 -