UCProgrammer
UCProgrammer

Reputation: 557

list remove() troubles

Remove() isn't working properly for me in this case where I am trying to remove elements from my list that do not contain a colon. Here is my list;

myList = ['hosts:127.0.0.1','-nU','-nT','-cA','-nB']

Doing separated = myList.split(',') and then

for i in separated:
    if ':' not in i:
    separated.remove(i)

print separated

leaves me with ['hosts:127.0.0.1', '-nT', '-nB'] as my output. I'm assuming this is because remove() only removes the first matching element. That still doesn't explain why -nt and -nb would be there though. What would a good alternative be to doing this?

Thanks

Upvotes: 0

Views: 64

Answers (3)

RishiC
RishiC

Reputation: 826

Use a for loop to go through each element of the list Like this for i in range(0,len(myList)-1): if ":" not in myList[i]: myList.remove(myList[i])

Upvotes: 0

FlyingTeller
FlyingTeller

Reputation: 20472

The problem is that you are looping over the list as you are deleting elements. Consider this small alteration to your code:

myList = ['hosts:127.0.0.1','-nU','-nT','-cA','-nB']
for i in myList :
    print(i)
    if ':' not in i:
         myList.remove(i)

Output:

hosts:127.0.0.1
-nU
-cA

So your for loop never actually looks at two of the entries of the list. You might consider using a list comprehension here as jpp has suggested.

Upvotes: 1

jpp
jpp

Reputation: 164653

Do not modify your list as you iterate over it.

Use a copy instead or, more idiomatically, a list comprehension:

separated = [i for i in myList if ':' in i]

Upvotes: 7

Related Questions