Reputation: 411
contacts.remove((name,ip))
I have the ip and it's 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.
Upvotes: 3
Views: 14117
Reputation: 1817
This answers my not created question. Thanks for the explanation, but let me summarize and generalize the answers for multiple deletion and Python 3.
list = [('ADC', 3),
('UART', 1),
('RemoveMePlease', 42),
('PWM', 2),
('MeTooPlease', 6)]
list1 = [(d, q)
for d, q in list
if d not in {'RemoveMePlease', 'MeTooPlease'}]
print(list1)
for i, (d, q) in enumerate(list):
if d in {'RemoveMePlease', 'MeTooPlease'}:
del(list[i])
print(list)
Upvotes: 1
Reputation: 881635
Since the ip
to remove is unique, you don't need all the usual precautions about modifying a container you're iterating on -- thus, the simplest approach becomes:
for i, (name, anip) in enumerate(contacts):
if anip == ip:
del contacts[i]
break
Upvotes: 4
Reputation: 82934
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.
Upvotes: 11