Duplicating list of lists [newbie]

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sun Mar 23 12:28:23 EDT 2008


Yatsek:
> Is there simple way to copy a into b (like a[:]) with all copies of
> all objects going as deep as possible?

If you only want to copy up to level-2, then you can do something
like:
cloned = [subl[:] for subl in somelist]
Or sometimes safer:
cloned = [list(subl) for subl in somelist]

If you want to go all the way down, you can use the deepcopy function
of the copy module. In many situations the level-2 copy may be enough,
and it can be faster.

Bye,
bearophile



More information about the Python-list mailing list