Removing elements from a list containing specific characters

I want to remove all elements in a list which contains (or does not contain) a set of specific characters, however I’m running in to problems iterating over the list and removing elements as I go along. Two pretty much equal examples of this is given below. As you can see, if two elements which should be removed are directly following each other, the second one does not get removed.

Im sure there are a very easy way to do this in python, so if anyone know it, please help me out – I am currently making a copy of the entire list and iterating over one, and removing elements in the other…Not a good solution I assume

>>> l
['1', '32', '523', '336']
>>> for t in l:
...     for c in t:
...         if c == '2':
...             l.remove(t)
...             break
...             
>>> l
['1', '523', '336']
>>> l = ['1','32','523','336','13525']
>>> for w in l:
...     if '2' in w: l.remove(w)
...     
>>> l
['1', '523', '336']

Figured it out:

>>> l = ['1','32','523','336','13525']
>>> [x for x in l if not '2' in x]
['1', '336']

Would still like to know if there is any way to set the iteration back one set when using for x in l though.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

List comprehensions:

l = ['1', '32', '523', '336']

[ x for x in l if "2" not in x ]

# Returns: ['1', '336']

[ x for x in l if "2" in x ]

# Returns: ['32', '523']
l = ['1', '32', '523', '336']
stringVal = "2"

print(f"{[ x for x in l if stringVal not in x ]}")

# Returns: ['1', '336']

print(f"{[ x for x in l if stringVal in x ]}")

# Returns: ['32', '523']

Method 2

If I understand you correctly,

Example:

l = ['1', '32', '523', '336']

[x for x in l if "2" not in x]

# Returns: ['1', '336']

fString Example:

l = ['1', '32', '523', '336']

stringVal = "2"

print(f"{[x for x in l if stringVal not in x]}")

# Returns: ['1', '336']

might do the job.

Method 3

In addition to @Matth, if you want to combine multiple statements you can write:

l = ['1', '32', '523', '336']

[ x for x in l if "2" not in x and "3" not in x]

# Returns: ['1']

fString Example

l = ['1', '32', '523', '336']

stringValA = "2"
stringValB = "3"

print(f"{[ x for x in l if stringValA not in x and stringValB not in x ]}")

# Returns: ['1']

Method 4

Problem you could have is that you are trying to modify the sequence l same time as you loop over it in for t loop.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x