OR operation not working in removing string part

Question:

I’ve been trying to parse a string and to get rid of parts of the string using the remove() function. In order to find the part which I wanted to remove I used an OR operator. However, it does not produce the outcome I expected. Can you help me?

My code looks like this:

import numpy as np

x = '-1,0;1,0;0,-1;0,+1'

x = x.split(';')

for i in x:
    if ('+' in i) or ('-' in i):
        x.remove(i)
    else:
        continue
    
x = ';'.join(x)    
print(x)

The outcome I expect is:

[1,0]

Instead the outcome is:

[1,0;0,+1]

Asked By: Fab

||

Answers:

Modifying lists that you are currently iterating over is not a good approach. Instead take a new list and append values in else.

x = '-1,0;1,0;0,-1;0,+1'

x = x.split(';')

new = []

for i in x:
    if ('+' in i) or ('-' in i):
        pass
    else:
        new.append(i)
    
x = ';'.join(new)    
print(x)

Gives #

1,0
Answered By: Bhargav

In your example there is a problem.

x = '-1,0;1,0;0,-1;0,+1'.split(';')

counter = 0
for i in x:
    counter +=1
    if '+' in i or '-' in i:
        x.remove(i)

print(x, counter)

Look at this. U modify a list over which u iterate.
If u remove n’th element, the (n+1) has now index n, (n+2) has n+1 so …
U skips some elements

In my opinion better solution is to use list comprehension:

x = '-1,0;1,0;0,-1;0,+1'.split(';')

expected_result = [el for el in x
                   if "-" not in el and
                   "+" not in el]

Or for loop but creates new list

expected_2 = []
for i in x:
    if '+' not in i and '-' not in i:
        expected_2.append(i)