0

I have a list of lists, in which I would like to modify some elements, but I don't wont to alter the original list of lists.

I have made a little example, which illustrates the problem I'm having.

# The original list of lists

hej = [[1,2,3,4],[1,2,3,4]]

# Now create a copy to modify elements in

dig = hej[:]

# Modify some element

dig[1][2] = 7

# Now printing both "dig" and "hej" returns the following

[[1,2,3,4],[1,2,7,4]]

# where I expected "hej" to return

[[1,2,3,4],[1,2,3,4]]

# and "dig" to return

[[1,2,3,4],[1,2,7,4]]

# I assumed that the way of copying also worked for a list of lists but
# that is not the case.

# for a single list, the behaviour is as expected

hej_1 = [1,2,3,4,5]
dig_1 = hej_1[:]
dig_1[3] = 10

#"dig_1" returns
[1,2,3,10,5]

#"hej_1" returns
[1,2,3,4,5]

So, my question is what is it that I'm missing about the difference in the way of copying when used on a list of lists?

Kristian Nielsen
  • 159
  • 1
  • 11
  • 1
    You need to *nest* the copying also, otherwise when you create a copy of the top list, you get references to the sub-lists. – Dani Mesejo Jan 08 '19 at 15:15
  • 1
    You only made a *shallow* copy of `hej`. Use `dig = [sub[:] for sub in hej]` to copy the nested lists explicitly, or use the `copy.deepcopy()` function to make a copy of arbitrary depth. See the duplicate. – Martijn Pieters Jan 08 '19 at 15:16
  • 1
    @StephenRauch: no, they are *not* the same object,, because `hej` was created from a shallow copy of the `dig` list: `hej = dig[:]`. `hej` is a distinct, separate ilst object. The **values** in that list are the same as the values in the `dig` list. – Martijn Pieters Jan 08 '19 at 15:16
  • @DanielMesejo and MartijnPieters Thank you for the clarification, it did the trick! – Kristian Nielsen Jan 08 '19 at 15:23

0 Answers0