venkat
venkat

Reputation: 1263

How to remove a tuple from the list

Here is my list of tuple:

[('Abbott', 'Texas'), ('Abernathy', 'Texas'), ('Abilene', 'Texas'), ('Ace', 'Texas'), ('Ackerly', 'Texas'), ('Alba', 'Texas'),('Addison', 'Texas'), ('Adkins', 'Texas'), ('Adrian', 'Texas'), ('Afton', 'Texas'), ('Agua Dulce', 'Texas'), ('Aiken', 'Texas'), ('Alamo', 'Texas'), ('Alanreed', 'Texas'), ('Albany', 'Texas')]

From the above tuple list i want to remove ('Alba', 'Texas')

I tried many ways doing it,but it is not giving me expected result.

I've tried

[x for x in listobj if any(y is not Alba for y in x)] 

Upvotes: 7

Views: 56864

Answers (4)

GalacticRaph
GalacticRaph

Reputation: 952

If you want to remove a tuple by its first element:

tup = [('hi', 'bye'), ('one', 'two')]
tup_dict = dict(tup) # {'hi': 'bye', 'one': 'two'}
tup_dict.pop('hi')
tup = list(tuple(tup_dict.items()))

Upvotes: 3

Yaroslav Surzhikov
Yaroslav Surzhikov

Reputation: 1608

list_of_tuples.remove(('Alba', 'Texas'))

or

list_of_tuples.pop(list_of_tuples.index(('Alba', 'Texas')))

Upvotes: 14

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8039

You can remove it by value:

your_list.remove(('Alba', 'Texas'))

But keep in mind that it does not remove all occurrences of your element. If you want to remove all occurrences:

your_list = [x for x in your_list if x != 2] 

Anyway, this question already answered so many times, and can be easily found - remove list element by value in Python.

Upvotes: 3

sg.sysel
sg.sysel

Reputation: 163

Using Python's list comprehension should work nicely for you.

foo = [('Abbott', 'Texas'), ('Abernathy', 'Texas'), ('Abilene', 'Texas'), ('Ace', 'Texas'), ('Ackerly', 'Texas'), ('Alba', 'Texas'),('Addison', 'Texas'), ('Adkins', 'Texas'), ('Adrian', 'Texas'), ('Afton', 'Texas'), ('Agua Dulce', 'Texas'), ('Aiken', 'Texas'), ('Alamo', 'Texas'), ('Alanreed', 'Texas'), ('Albany', 'Texas')]
foo = [x for x in foo if x!= ("Alba", "Texas")]

Upvotes: 3

Related Questions