0

So I have a list D = [[1030, 1200], [1300, 1600], [1800, 1830]] and I made a copy called E: E = D[:] then I tried to operate on it with a function: covertToMin(E). However the function also operated on D which doesn't make sense because they have separate locations in memory. I am pretty confused and appreciate any help!

    E = D[:]
    for i in range(len(E)):
        for j in range(0,2):
            E[i][j] = convertToMinutes(E[i][j])
    print(id(E))
    print(id(D))
    print(D)
    print(E)

def convertToMinutes(time):

    if time < 1000:
        time = str(time)
        minutes = time[1:]
        hourmin = int(time[0])* 60 

        time = int(minutes) + (hourmin)
    else: 
        time = str(time)
        minutes = time[2:]
        hourmin = int(time[:2]) * 60
        time = int(minutes) + hourmin
    return time

The output I receive is:

4368232032 
4368231552
[[690, 720], [900, 960], [1080, 1110]]
[[690, 720], [900, 960], [1080, 1110]]
norok2
  • 25,683
  • 4
  • 73
  • 99
tsm
  • 419
  • 4
  • 11

2 Answers2

0

I recommend you to use python deepcopy for your problem. The documentation page is clear and it will shed some light on it.

import copy
E = copy.deepcopy(D)
Sorin Dragan
  • 510
  • 4
  • 9
0

I think the problem is that Python does not create a different list when you "equal" list variables (or dicts). To do that, you need to use deepcopy()

Try this in your code:

import copy

E = copy.deepcopy(D)

This will really generate two separate lists.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Kalma
  • 111
  • 2
  • 15
  • The slice notation `D[:]` does actually make a copy, it's the generally accepted way of doing it. The problem is that it doesn't make copies of the lists inside. The original code would have worked fine if it wasn't a list of lists. – Mark Ransom Dec 07 '19 at 18:56
  • Just to clarify the answer slightly, copy only do a shallow copy (same as `E = D[:]`), so elements in `E` and `D` refer to the same objects. I.e. `id(E[0])` and `id(D[0])` are equal. – user2653663 Dec 07 '19 at 18:57
  • Thanks for the clarifications. That was something weird to me the first time I found this very same problem. – Kalma Dec 07 '19 at 19:00