-1

I am currently attempting to create a list of ranges for letters in my program. I have done this through having a temp variable 'censorRange' to grab the range for an instance, then appending that variable to a 'censors' variable to be returned at the end of the function.

The issue is that when I change the 'censorRange' variable it also changes elements in the 'censors' variable. As an example: Initially, 'censorRange' = [10,15], and 'censors' = [[10,15]]. When I debug the program when 'censorRange' goes from '[10,15]' to '[17,23]' then 'censors' will also go to [[17,23]]. Then at the end of the program censors will give me [[17,23],[17,23]] instead of [[10,15],[17,23]].

Why does this occur, and how can I fix the problem? I have attached the code I have been using below. If you have any suggestions please do tell me, I have been getting frustrated over this for a while now. Thank you in advance.

Code:

censors = []
censorRange = [None, None]
for match in matches:
    if((censorRange[0] != None) and (censorRange[1] != None)
       and (match.span()[0] > censorRange[1])):
            if(not lettersBetween(text, censorRange[1], match.span()[0], 5)):
                censorRange[1] = match.span()[1]
                censors.pop()
                censors.append(censorRange)
                censorRange[1] = match.span()[1]
            else:
                censors.append(match.span())
                censorRange[0] = match.span()[0]
                censorRange[1] = match.span()[1]
    else:
        censors.append(match.span())
        censorRange[0] = match.span()[0]
        censorRange[1] = match.span()[1]
return censors
F Mckinnon
  • 367
  • 1
  • 4
  • 9
  • You add `censorRange` to `censors` at `censors.append(censorRange)`. If you alter `censorRange`, you'll see that change in `censors` as well. If you don't want that, you'll need to make a copy of the inner list before adding it to `censors`. A copy of the list isn't made when it's added to the other list. If you change a list in one place, it will effect that list wherever it is. – Carcigenicate Jul 06 '19 at 23:59

1 Answers1

1

When you add a list to another list, it does not automatically make a copy. If you want to do that, you have to explicitly state so:

censors.append(censorRange.copy())
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
  • Please do not answer a question that has already been voted to be closed. Your answer just re-hashes what's in the linked question. We get so many questions of this exact nature. It's best just to point them to the established answers once you have sufficient rep. – Carcigenicate Jul 07 '19 at 00:11
  • 1
    @Carcigenicate But his question is not on how to make a copy. His question is on the cause of the error.. – Akaisteph7 Jul 07 '19 at 00:29