Reputation: 952
I have a list of strings containing IP addresses and DNS names with which I would like to remove the values beginning with "10." only. The sample data is as follows:
['www.example.com','1.2.3.4','4.3.2.1','example.net','10.1.1.10','10.1.1.11',...]
I thought this would be simple and started with the following:
for v in address:
test = re.match('(^\d+\.)',v)
if test:
if test.group(1) == '10.':
address.remove(v)
The "10." addresses were not removed although I didn't receive any errors (and did some t-shooting with "print address.remove(v)" which resulted in "None" for each "10." address. Leads me to believe the regex is wrong but it seems to work other than in this capacity.
So I poked around with re.purge() - this didn't help either but don't think it's a factor in my problem. I also tried using del address[...] to no avail.
Where have I gone wrong?
Thanks very much for your attention.
Upvotes: 3
Views: 27489
Reputation: 141998
One way is to create a new list
using a list comprehension and str.startswith()
:
>>> [a for a in address if not a.startswith('10.')]
['www.example.com', '1.2.3.4', '4.3.2.1', 'example.net', '...']
This avoids using regular expressions and removing items during iteration, but does create a copy.
Upvotes: 3
Reputation: 40871
The easy way would be to use list comprehensions:
filtered = [ v for v in address if not v.startswith('10.') ]
Upvotes: 14
Reputation: 4199
If would probably make sense to test first that there is really an IP address in question.
Otherwise 10.some-cdn.some-mighty-corp.com will be filtered out.
Upvotes: 1
Reputation: 9537
What you've done wrong here is iterating over a list while you're changing the list. That means the iteration gets confused.
See Removing Item From List - during iteration - what's wrong with this idiom? for some suggestions on how to do this correctly.
Upvotes: 1