sia
sia

Reputation: 411

remove from a list of tuples according to the second part of the tuple in python

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

Answers (3)

Himura
Himura

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)

The corresponding help topic

Upvotes: 1

Alex Martelli
Alex Martelli

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

John Machin
John Machin

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

Related Questions