what options clone or copy list in python? using new_list = my_list modifies new_list every time my_list changes. why this? with new_list = my_list , don't have 2 lists. assignment copies reference list, not actual list, both new_list , my_list refer same list after assignment. to copy list, have various possibilities: you can slice it: new_list = old_list[:] alex martelli's opinion (at least back in 2007 ) is, it weird syntax , not make sense use ever . ;) (in opinion, next 1 more readable). you can use built in list() function: new_list = list(old_list) you can use generic copy.copy() : import copy new_list = copy.copy(old_list) this little slower list() because has find out datatype of old_list first. if list contains objects , want copy them well, use generic copy.deepcopy() : import copy new_list = copy.deepcopy(old_list) obviously slowest , memory-needing method, unavoidable. example: import copy class foo(object): ...
Comments
Post a Comment