string issue
Terry Reedy
tjreedy at udel.edu
Fri Feb 4 16:52:30 EST 2005
"Steve Holden" <steve at holdenweb.com> wrote in message
news:36QMd.103084$Jk5.36127 at lakeread01...
> You are modifying the list as you iterate over it. Instead, iterate over
> > a copy by using:
> for ip in ips[:]:
Or if you are only deleting items, you can iterate backwards.
You can also build a new list with only the items you want. Do this either
with an explicit loop or even better, use filter or a list comp.
ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98',
'127.0.0.1', '255.0.0.0', '255', '128.173.255.34']
# 2.2 requires single char for 'not in string' test
ips2 = []
for ip in ips:
if ip.find('255') == -1: ips2.append(ip)
print ips2
print filter(lambda ip: ip.find('255') == -1, ips)
print [ip for ip in ips if ip.find('255') == -1]
# thrice prints
['128.173.120.79', '198.82.247.98', '127.0.0.1']
This seems much more sensible to me than building a new list with
everything (a copy), including things you don't want, and then deleting the
things you don't want (an O(n**2) operation).
Terry J. Reedy
More information about the Python-list
mailing list