🎓 A1Learner
🔍

Python Copy & Join Lists

A copy of a list is a new list that holds the same items as another list. Joining puts the items of two lists into one list.

Two names, one list

Here b = a makes no new list. Both names point to the same list.

a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)

Make a copy with copy()

Now the append touches only the copy.

a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)
print(b)

Two more ways to copy

list() and a full slice [:] each make a new list too.

a = ["x", "y"]
b = list(a)
c = a[:]
b.append("z")
c.append("w")
print(a)
print(b)
print(c)

Join lists two ways

The + sign builds a new list. extend() grows the first list in place.

start = [1, 2]
end = [3, 4]
print(start + end)
start.extend(end)
print(start)

Example

playlist = ["Song A", "Song B", "Song C"]
backup = playlist.copy()
backup.append("Song D")
backup.remove("Song A")
print(playlist)
print(backup)

Key points

  • Copy: a new list that holds the same items as another list
  • Use copy(), list(), or a full slice [:] to make a copy
  • Use + to join two lists into a new list
  • Use extend() to add all items of one list onto the end of another
  • It gives one list two names, so edits through b change what a shows too.

In this example, playlist holds three song names. copy() makes a second list and saves it as backup. append() adds Song D to the backup only. remove() then takes Song A out of the backup only. The first print shows the first playlist, still whole. The second print shows the edited backup.

Note

b = a is not a copy.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

After a = [1, 2] and b = a, then b.append(3), what is a?