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
1# 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.
After this program
If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.