Copy a list of list by value and not reference

Because python passes lists by reference

This means that when you write “b=a” you’re saying that a and b are the same object, and that when you change b you change also a, and viceversa

A way to copy a list by value:

new_list = old_list[:]

If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

import copy
new_list = copy.deepcopy(old_list)

Leave a Comment