0

So I have the variable test, that accesses an item of a 2-dimensional array. Then, I want to change one item of test, but not from the original array. But somehow, it still changes it although I stored the value in a seperate variable. Here's my code:

config = [[1, 2], [3, 4], [5, 6]]

test = config[0]

test[0] = 45                                               

print(config)

When I run this, the first element of the first array of config has changed to 45, so config is now:

config = [[45, 2], [3, 4], [5, 6]]

Can anybody explain this behaviour and help me so that when I change a element of test, config doesn't change?

*Edit: I don't think it is a duplicate of an other question, because I've already tried:

*Note: after each option, obviously test = temp_config[0] is run instead of test = config[0].

1: temp_config = config.copy()

2: temp_config = config[:]

3: temp_config = []; temp_config.extend(config)

4: temp_config = list(config)

5: temp_config = list(config)

6: temp_config = copy.copy(config)

7: temp_config = [i for i in config]

8: temp_config = []; for item in config: temp_config.append(item)

While editing this question, I noticed that ONLY copy.deepcopy() works, NONE of the other suggested options.

by James
  • 89
  • 10
  • 1
    @Austin OP has nested lists. They need a `deepcopy`. Consider changing the duplicate target to the following: [How to deep copy a list?](https://stackoverflow.com/questions/17873384/how-to-deep-copy-a-list) – Georgy Aug 09 '19 at 13:42

1 Answers1

0

Make config readonly or copy config to a tempConfig and do operations on tempConfig while config will remain intact