string issue

Bill Mill bill.mill at gmail.com
Fri Feb 4 14:34:39 EST 2005


On Fri, 04 Feb 2005 14:23:36 -0500, rbt <rbt at athop1.ath.vt.edu> wrote:
> Either I'm crazy and I'm missing the obvious here or there is something
> wrong with this code. Element 5 of this list says it doesn't contain the
> string 255, when that's *ALL* it contains... why would it think that???
> 
> import time
> 
> 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']
> 
> for ip in ips:
>      if '255' in ip:
>          try:
>              print "Removing", ip
>              ips.remove(ip)
>          except Exception, e:
>              print e
> 
> print ips
> time.sleep(5)
> 

You're gong crazy:

>>> 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']
>>> for ip in ips:
...     if '255' in ip: print ip
...
255.255.255.255
255.0.0.0
255
128.173.255.34

The problem is that you're operating in-place on an array while it's
being iterated over. Since the iterator is only created once, you're
can't change the array while you're iterating over it. Instead, try a
list comprehension:

>>> ips = [ip for ip in ips if '255' not in ip]
>>> ips
['128.173.120.79', '198.82.247.98', '127.0.0.1']

Peace
Bill Mill
bill.mill at gmail.com



More information about the Python-list mailing list