contacts.remove((name,ip)) i have the ip and its unique, i want to remove this tuple from contacts according to the ip and no need to name, i just tried this "contacts.remove((pass,ip))", but i encountered an error.
views:
69answers:
3
+2
A:
contacts = [(name, ip) for name, ip in contacts if ip != removable_ip]
or
for x in xrange(len(contacts) - 1, -1, -1):
if contacts[x][1] == removable_ip:
del contacts[x]
break # removable_ip is allegedly unique
The first method rebinds contacts to a newly-created list that excludes the desired entry. The second method updates the original list; it goes backwards to avoid being tripped up by the del statement moving the rug under its feet.
John Machin
2010-05-17 23:00:13
A:
This goes thought the contacts and removes any list which second item is the wanted ip:
for c in contacts:
if c[1] == wanted_ip:
contacts.remove(c)
A second safer option is this:
contacts = original_contacts[:]
for c in contacts:
if hasattr(c, '__iter__'):
if len(c) == 2:
if c[1] == wanted_ip:
contacts.remove(c)
None
2010-05-17 23:51:18
Neither is safe.
John Machin
2010-05-18 01:15:33
A:
Since the ip to remove is unique, you don't need all the usual precautions about modifying a contained you're iterating on -- thus, the simplest approach becomes:
for i, (name, anip) in enumerate(contacts):
if anip == ip:
del contacts[i]
break
Alex Martelli
2010-05-18 05:35:53