3

I understand where my problem is stemming from, I simply do not know how to fix it.

for x in listoflists:
    if x[1] == [1,0]:
        q=[0, 0]
        for z in range(5):
            q[z] = x[:]
            q[z][1] = [0,1]
            q[z][0][-1] = q[z][0][-1] * 1.25
            print(id(q[z][0][-1]))
        list.append(q)

What I am trying to do is:

  1. go into some data that I have gathered and make copies where I have switched a data label from [1,0] to [0,1]
  2. then go into the zero index and multiply the price column by some factor to scale it up.

What I currently have is changing all prior values to be what I want the last value to be.

I understand this is something to do with python handling lists as references.

I had to change my first line to be a slice of x to alleviate this, but I do not know how to get around the parts where I take specifically indexed list items because it is showing the id as two different memory spaces.

All of the solutions I have seen show list comprehensions but I do not know how that applies to my case, because it seems like my z indexing is working correctly and they all have separate memory ids.

dot.Py
  • 5,007
  • 5
  • 31
  • 52
Ryan Chesler
  • 45
  • 1
  • 5
  • 6
    The description is rather hard to follow, an MCVE with input and expected result/output would do wonders for people trying to comprehend your desired behavior. – timgeb Apr 11 '17 at 16:04
  • 2
    The problem is that `x[:]` makes a shallow copy of `x`. You need to make a deep copy so you copy the next level. – Barmar Apr 11 '17 at 16:07

1 Answers1

2

You need to do deep copy. Slicing does shallow copy.

from copy import deepcopy

lst1 = ['a','b',['ab','ba']]

lst2 = deepcopy(lst1)
id(lst1[2])
# 4451912
id(lst2[2])
# 51003144
Afaq
  • 1,146
  • 1
  • 13
  • 25