To copy a list in python, a solution is to use the "built-in" function list(), example:
>>> L1 = ['a','b','c','d','e','f']
>>> L2 = list(L1)
>>> L2
['a', 'b', 'c', 'd', 'e', 'f']
Another solution is to use the list comprehension:
>>> L1 = ['a','b','c','d','e','f']
>>> L2 = [i for i in L1]
>>> L2
['a', 'b', 'c', 'd', 'e', 'f']
WARNING: to copy a list do not use the = operator, because the two lists will be then linked (in other words if you change a list the other list will be modified as well)
>>> L1 = ['a','b','c','d','e','f']
>>> L2 = L1
>>> L1
['a', 'b', 'c', 'd', 'e', 'f']
>>> L2
['a', 'b', 'c', 'd', 'e', 'f']
>>> del L2[0]
>>> L2
['b', 'c', 'd', 'e', 'f']
here by editing the L2 list, we also changed L1:
>>> L1
['b', 'c', 'd', 'e', 'f']
References
Links | Site |
---|---|
list | Python Doc |
How to clone or copy a list in Python? | stackoverflow |