1

So I had a very unusual problem with deleting elements from lists, I have recreated the problem in a much smaller and easier to understand format. Basically deleting an item from a list will delete the same item from a different list you have previously set equals to the original list outside of the main loop.

a = [1,2,3,4]
b = a

while True:
    print("a:", a)
    print("b:", b)
    c = int(input("delete"))
    del(a[c])
    print("a:", a)
    print("b:", b)
    break

This returns:

a: [1, 2, 3, 4]
b: [1, 2, 3, 4]
delete2 #the "2" is my input
a: [1, 2, 4]
b: [1, 2, 4]
>>> 

I researched and saw a few things about shallow/deep copies, but i'm not too sure about that, if anyone could shed some more light that would be great

Taiwo
  • 15
  • 6
  • *"saw a few things about shallow/deep copies"* - and you're using **neither**. http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – jonrsharpe Mar 21 '17 at 22:26
  • Possible duplicate of [How to clone or copy a list?](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – TemporalWolf Mar 21 '17 at 22:28
  • "....but i'm not too sure about that, if anyone could shed some more light that would be great", sorry if I've annoyed you, but thanks for the link – Taiwo Mar 21 '17 at 23:08

1 Answers1

3

This is because a and b are names of the same list (or more formally, references to the same object).

To create a name for a new list make a copy of it:

b = list(a)
# or
b = a[:]

This will create a new list containing the exact same members and is called shallow-copy.

A deep-copy is when you recursively copy the entire structure but it seems like its not needed here.

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • When someone actually gives an example of what he did that works and shows he bothered to try and understand, I think I'll contribute two minutes to explain. The duplicate target is not very good at the moment but I'm sure there are good duplicate targets. – Reut Sharabani Mar 21 '17 at 22:31
  • Thanks a lot for the answer, i'll look into the duplicate targets – Taiwo Mar 21 '17 at 23:08