-2

I would like to copy the following list:

startTimeList = [[0, 0], [2, 0], [4, 0], [6, 0], [8, 0], [10, 0], [12, 0], [14, 0], [16, 0], [18, 0], [20, 0], [22, 0]]

Then store this copy of startTimeList as a list called endTimeList. And subsequently change this copy so that the every last element of the nested list (which is currently 0) is changed to the value of a variable called flowDuration (which is now set at 10).

Then the endTimeList should look like this:

[[0, 10], [2, 10], [4, 10], [6, 10], [8, 10], [10, 10], [12, 10], [14, 10], [16, 10], [18, 10], [20, 10], [22, 10]]

This is the code I have for this right now:

startTimeList = [[0, 0], [2, 0], [4, 0], [6, 0], [8, 0], [10, 0], [12, 0], [14, 0], [16, 0], [18, 0], [20, 0], [22, 0]] # the initial list that has to be transformed into endTimeList
flowDuration = 10

endTimeList = startTimeList.copy() # copies the startTimesList and stores this copy as endTimesList

for y in endTimeList: 
    y[1] = flowDuration # for every nested list in the startTimeList, changes the first index (which is the second element of the nested list) into a variable called flowDuration (which is currently 10)

print(startTimeList)
print(endTimeList)

However, when I run this code, somehow startTimeList has also changed from its original values, while this list should stay the same. These are the values of startTimeList en endTimeList that I get when I print them:

startTimeList: [[0, 10], [2, 10], [4, 10], [6, 10], [8, 10], [10, 10], [12, 10], [14, 10], [16, 10], [18, 10], [20, 10], [22, 10]]

endTimeList: [[0, 10], [2, 10], [4, 10], [6, 10], [8, 10], [10, 10], [12, 10], [14, 10], [16, 10], [18, 10], [20, 10], [22, 10]]

and these would be the desired values:

startTimeList: [[0, 0], [2, 0], [4, 0], [6, 0], [8, 0], [10, 0], [12, 0], [14, 0], [16, 0], [18, 0], [20, 0], [22, 0]]
endTimeList: [[0, 10], [2, 10], [4, 10], [6, 10], [8, 10], [10, 10], [12, 10], [14, 10], [16, 10], [18, 10], [20, 10], [22, 10]]

How can it be possible that the startTimeList is also altered, while I made sure to only edit the copy called endTimeList?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

2

In Python, objects are passed by reference, which means that changes to an object will affect all the references of that object. When you copy a list, it creates a shallow copy, meaning only the top level of items is copied - the references to the inner lists still point to the same place. If you want to copy everything in the list, you want to use deepcopy from the copy module.

from copy import deepcopy

endTimeList = deepcopy(startTimeList)
Miguel Guthridge
  • 1,444
  • 10
  • 27
  • 1
    And [the docs](https://docs.python.org/3.10/library/copy.html?highlight=deepcopy#copy.deepcopy) have a good explanation of shallow and deep copies too – Freddy Mcloughlan Jun 22 '22 at 11:46
1

That's the way to do what you want:

import copy
endTimeList = copy.deepcopy(startTimeList)
Jock
  • 388
  • 2
  • 12