LearnWave
Learn it. Master it.

Lists

Nested lists and copying

Copy a list without making an alias.

A list that is an element of another list is a nested list. Use two indices: list1[i][j] takes the i-th element (itself a list), and then its j-th element. For n = [3, [7, 8, 9], 5], n[1] is [7, 8, 9], and n[1][0] is 7.

Copying a list needs care. list2 = list1 does not make a copy. Both names now refer to the same list object: list2 is just another name for it (an alias). Any change made through one name shows up through the other.

To make a real, separate copy, use one of three methods:

  • Slicing: list2 = list1[:]
  • The list() function: list2 = list(list1)
  • The copy module: import copy, then list2 = copy.copy(list1)

Each of these creates a new list object, so changing one list no longer affects the other.

= shares; [:], list() and copy.copy() copy.
= shares; [:], list() and copy.copy() copy.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.