2

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]

Fab
  • 23
  • 4
  • 2
    Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – matszwecja Nov 30 '22 at 13:10

2 Answers2

2

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
1

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)