1

In python, inside a class, it appears that when I save a "self" variable into another one, if I edit the new variable, the "self" is also edited:

    undropped_lines = self.flagged_lines
    print self.flagged_lines
    del undropped_lines[0]
    print self.flagged_lines

How should one avoid this trait in the code?

Rui Lima
  • 227
  • 1
  • 4
  • 17

2 Answers2

4

This is because lists are mutable and when you say undropped_lines = self.flagged_lines you are just pointing a new name at the same instance.

If you want a copy use undropped_lines = self.flagged_lines[:]

Holloway
  • 6,412
  • 1
  • 26
  • 33
3

This is because undropped_lines and self.flagged_lines are pointing to the same data. Think of it as two different "names" pointing to the same entity.

You can get around this by creating a shallow copy of the list when assigning to undropped_lines. Something like:

undropped_lines = list( self.flagged_lines )
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71