Home>

If an element (string) of the array contains a particular symbol, i am trying to create an array with it removed.
Therefore, the list is divided into two parts, one for reference and the other for operation, and the element for operation is deleted.

The reference list has the problem that the number of elements in the array decreases even though the elements have not been deleted.
The situation is that the length of a list with a different name is also affected by the code that searches while the length of the list changes.

I've renamed the arrays separately and I don't know why this happens.
I haven't found a solution by searching.

candidate
9
result result
9
candidate
8
result result
8
candidate
7
result result
7
candidate
6
result result
6
candidate
Five
result result
Five
candidate
Four
result result
Four
Traceback (most recent call last):
  File "issue.py", line 19, in<module>
    elm = candidate [i]
IndexError: list index out of range
Corresponding source code
import re
ans = ['a','b','c','&','b--c','a/w','d','s.e','e']
#reference
candidate = []
#operation
result = []
candidate = ans
result = ans
Since #result is an array that changes elements, prepare candidate as an array that does not change
for i in range (len (candidate)):
    print ('candidate')
    print (len (candidate))
    print ('result')
    print (len (result))
    elm = candidate [i]
    if re.search ('--', elm):
        result.remove (elm)
    elif re.search ('/', elm):
        result.remove (elm)
    elif re.search ('.', Elm):
        result.remove (elm)
    elif re.search ('&', elm):
        result.remove (elm)
print (result)
Supplementary information (FW/tool version, etc.)

Python 3.7.4

  • Answer # 1

    Let's assign a copy of the list to candidate and result.

    candidate = ans.copy ()
    result = ans.copy ()

  • Answer # 2

    I've renamed the arrays separately and I don't know why this happens.

    Look up the ID, not the name of the array.

    import copy
    ans = ['a','b','c','&','b--c','a/w','d','s.e','e']
    candidate = ans
    result = ans
    print (f "ans id: {id (ans)}")
    print (f "candidate id: {id (candidate)}")
    print (f "result id: {id (result)}")
    candidate = copy.copy (ans)
    result = copy.copy (ans)
    print (f "ans id: {id (ans)}")
    print (f "candidate id: {id (candidate)}")
    print (f "result id: {id (result)}")
    ans id: 2272706510464
    candidate id: 2272706510464
    result id: 2272706510464
    copied ...
    candidate id: 2272706506048
    result id: 2272706379392

  • Answer # 3

    Since "reference" to the same array (ans) is set in candidate and result, I think this behavior is correct.
    As a countermeasure, it seems that one or both are copied.

    import copy
    ans = ['a','b','c','&','b--c','a/w','d','s.e','e']
    candidate = ans
    result = copy.copy (ans) # deepcopy for 2D and above