Python Practice › List Programs › Program 16

Copy a list

EasyList Programs · 16 of 100

Write a Python program to copy a list so that changing the copy does not change the original.

Advertisement
Input
[1, 2, 3]
Output
[1, 2, 3] [1, 2, 3, 4] [1, 2, 3]

Approach

  1. Use copy(), list() or slicing [:].

Solution

Python
original = [1, 2, 3]copy1 = original.copy()copy2 = original[:]copy1.append(4)print(original, copy1, copy2)
Output
[1, 2, 3] [1, 2, 3, 4] [1, 2, 3]

Line by line

Lines 2-3

Both create new lists.

Line 4

Changing the copy leaves the original alone.

Watch out

copy2 = original would not copy; both names would refer to the same list.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs