string issue

Steven Bethard steven.bethard at gmail.com
Fri Feb 4 14:32:30 EST 2005


rbt 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)
> 
> Someone tell me I'm going crazy ;)

You're going crazy. ;)

py> 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']
py> for ip in ips:
...     # debugging statement:
...     print "Looking at", ip
...     if '255' in ip:
...         try:
...             print "Removing", ip
...             ips.remove(ip)
...         except Exception, e:
...             print e
...
Looking at 255.255.255.255
Removing 255.255.255.255
Looking at 198.82.247.98
Looking at 127.0.0.1
Looking at 255.0.0.0
Removing 255.0.0.0
Looking at 128.173.255.34
Removing 128.173.255.34

Notice how elements of your list are being skipped.  The problem is that 
you're modifying a list while you iterate over it.

Why don't you try a list comprehension:

py> 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']
py> [ip for ip in ips if '255' not in ip]
['128.173.120.79', '198.82.247.98', '127.0.0.1']

Steve



More information about the Python-list mailing list