To copy the list in python, there are various possibilities. You can use the builtin list.copy()
method.
1 | new_list = old_list.copy() |
Below is an example to clone/copy a list in python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import copy class Foo(object): def __init__(self, val): self.val = val def __repr__(self): return str(self.val) foo = Foo(1) a = ['foo', foo] b = a.copy() c = a[:] d = list(a) e = copy.copy(a) f = copy.deepcopy(a) # edit orignal list and instance a.append('baz') foo.val = 5 print('original: %r\n list.copy(): %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r' % (a, b, c, d, e, f)) |
Program Output
1 2 3 4 5 6 | original: ['foo', 5, 'baz'] list.copy(): ['foo', 5] slice: ['foo', 5] list(): ['foo', 5] copy: ['foo', 5] deepcopy: ['foo', 1] |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.