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 browser
1# Program to clone a list
2
3items = input("Enter list elements separated by space: ").split()
4
5clone1 = items[:]
6clone2 = list(items)
7
8print("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.