0

I wrote this script:

soilMod = ['ptaaco']
n = 2

soilModSplit = [soilMod[i:i+n] for i in range(0, len(soilMod), n)] # This returns ['pt', 'aa', 'co']

alphaTest = soilModSplit # I want to maintain the original list built before I remove items below. This returns ['pt', 'aa', 'co'] as well

if 'pt' in soilModSplit:
      soilModSplit.remove('pt')
      print soilModList # This returns ['aa', 'co']
      print alphaTest # This also returns ['aa', 'co'] It's missing the original ['pt', 'aa', 'co'] and I didn't ask the script to remove it from this particular list.

For some reason, when I remove the item ('pt') from soilModSplit, it also removes the item from alphaTest. Is this the expected result? It seems like any variable built on the soilModSplit (in this case, alphaTest) is dependent on any action taken on the soilModSplit. Maybe I am doing something wrong? Is there a way to work around this?

Thanks, Mike

Mike
  • 4,099
  • 17
  • 61
  • 83
  • 1
    @JoeFrambach Although that fixes the problem, it doesn't answer the question – jamylak Jun 10 '13 at 19:54
  • Joe Frambach. I searched around and didn't find that post. Maybe if I used the 'Clone' keyword. That post actually answers a few other questions I had, so thanks for providing that to me. – Mike Jun 10 '13 at 20:02

2 Answers2

2
alphaTest = soilModSplit 

alphatest is just a another name for the same list binded to soilModSplit. Make a shallow copy:

alphaTest = list(soilModSplit )
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Thanks jamylak. I did not realize that it didn't make a copy. Very good to know. I implemented that into my script and i am getting the result I need :) – Mike Jun 10 '13 at 19:48
1

When you do alphaTest = soilModSplit, you are not creating a copy. You just have two names referencing the same list. If you want to save a copy, do alphaTest = list(soilModSplit).

BrenBarn
  • 242,874
  • 37
  • 412
  • 384