Clone / Copy List in Python
items[:] and list(items) copy the list, not the name. Change one, the other stays.
BeginnerList ProgramsExample 14 of 25
clone-copy-list.py
Run in browser1# Program to clone a list23items = input("Enter list elements separated by space: ").split()45clone1 = items[:]6clone2 = list(items)78print("Original:", items)9print("Clone1:", clone1)10print("Clone2:", clone2)
Output
Enter list elements separated by space: a b c Original: ['a', 'b', 'c'] Clone1: ['a', 'b', 'c'] Clone2: ['a', 'b', 'c']
What's going on
clone = items does not copy. Both names point at the same list. Mutate one, both change. That bug eats evenings.
items[:] and list(items) make a new list with the same elements. Nested lists are still shared (shallow copy). For this page the elements are strings, so you will not notice.