1

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)] 
halfer
  • 19,471
  • 17
  • 87
  • 173
venkat
  • 1,113
  • 2
  • 14
  • 35
  • What exactly did you try? and what does "not giving me result properly" entail? what does it give you? – Sayse Sep 11 '17 at 09:47
  • Is it really that hard to employ a search engine with a "remove item from list in python" query? – timgeb Sep 11 '17 at 09:48
  • 1) What have you tried? 2) Does order matter? – cs95 Sep 11 '17 at 09:49
  • [x for x in listobj if any(y is not Alba for y in x)] i think this is not proper one – venkat Sep 11 '17 at 09:51
  • 1
    @venkat It's certainly not proper. It won't even run. – cs95 Sep 11 '17 at 09:51
  • Does this answer your question? [How to remove specific element from an array using python](https://stackoverflow.com/questions/7118276/how-to-remove-specific-element-from-an-array-using-python) – Georgy Nov 09 '20 at 12:05

4 Answers4

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

or

list_of_tuples.pop(list_of_tuples.index(('Alba', 'Texas')))
Yaroslav Surzhikov
  • 1,478
  • 1
  • 7
  • 14
3

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")]
sg.sysel
  • 163
  • 5
2

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.

Oleh Rybalchenko
  • 5,265
  • 3
  • 20
  • 33
1

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 = tuple(tup_dict.items()) # (('one', 'two'),)
GalacticRaph
  • 752
  • 7
  • 11
  • To fall back on a list of tuple as the first line input, the last line should include `list()` and read as: `tup = list(tuple(tup_dict.items()))` – JV conseil Jun 03 '20 at 17:16