AnsweredAssumed Answered

Removing list elements

Question asked by jborgion on Feb 2, 2018
Latest reply on Feb 2, 2018 by Dan_Patterson

I have a list of strings that may contain special characters.  I'd like to loop through that list and remove any elements that have special characters.  

import string

mylist = ['joe', 'dan', '#joe', 'd@n']

for name in mylist:
     if any(c in string.punctuation for c in name):
         mylist.remove(name)

>>>mylist
['joe', 'dan', 'd@n']

# so the 'for name in mylist' approach
# quits after finding #joe, leaving d@n
# let's try another approach....

mylist = ['joe', 'dan', '#joe', 'd@n']

>>> for i in range(len(mylist)):
     if any(c in string.punctuation for c in mylist[i]):
         mylist.remove(mylist[i])
        
Runtime error
Traceback (most recent call last):
  File "<string>", line 2, in <module>
IndexError: list index out of range

>>> mylist
['joe', 'dan', 'd@n']

Okay, I get the out of range error since it has removed one element and len(mylist) is no longer 4; how do I plow through a list  and remove all the bad-guys without stopping or tossing an error?  

mylist = ['joe', 'dan', '#joe', 'd@n']
try:
  for i in range(len(mylist)):
    if any(c in string.punctuation for c in mylist[i]):
      mylist.remove(mylist[i])
except IndexError:
  pass
     
>>> mylist
['joe', 'dan', 'd@n']

Here, the error is suppressed, but I'm still left with that pesky d@n....

Outcomes