0

Is there any problem between using the pop method and for loops when we they are not using the same variables as each other?

This is my code.

def tagsnotused(self):

    tag_list = self.Tags
    tag_list_Names = []
    # ~ append list by object Name to use index method later
    for Tag in self.Tags:
        tag_list_Names.append(Tag.Name)

    for Tag in self.Tags:   
        # ~ a = 0 tag processed, a = 1 tag not processed
        a = 0
        # ~ Adding tails
        TagName0 = Tag.Name + "."
        TagName1 = Tag.Name + "["
        TagName2 = Tag.Name + ")"
        # ~ Loop for looking conditions
        for Prog in self.Program:
            for Rout in Prog.Routine:
                for Rng in Rout.Rung:
                    # ~ Condicional para encontrar tag
                    if (Rng.Content.find(TagName0) != -1 or Rng.Content.find(TagName1) != -1 or  Rng.Content.find(TagName2) != -1) and a == 0:
                        a = 1
                        index = tag_list_Names.index(Tag.Name)
                        value = tag_list.pop(indice)
                        tag_list_Names.pop(indice)



    return tag_list 

The problem is that everytime I am making value = tag_list.pop(indice) the for loop is jumping one element and going to the next one.

self.Tags is as follows list[_object]

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Jmm86
  • 103
  • 8
  • Note that ``tag_list = self.Tags`` does not create a copy of ``self.Tags``, it merely refers to the value of ``self.Tags`` with an additional name. See also [If two variables point to the same object, why doesn't reassigning one variable affect the other?](https://stackoverflow.com/questions/56667280/if-two-variables-point-to-the-same-object-why-doesnt-reassigning-one-variable) – MisterMiyagi Apr 02 '20 at 12:50

1 Answers1

2

You are getting bitten by the mutability of lists.

taglist = self.Tags causes taglist to point towards the same list as self.Tags

In order to fix this you could use the copy module.

from copy import copy

And then to create the copy of your list use taglist = copy(self.Tags).

You could also simply use taglist = self.Tags[:].

What's happening in your loop is you are iterating over self.Tags and when you pop() the element out of taglist it removes it from self.Tags as well since they are both pointing at the same object. This causes your for loop to "jump ahead" since you now have one less element in it.

Axe319
  • 4,255
  • 3
  • 15
  • 31