7

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)] 
6
  • What exactly did you try? and what does "not giving me result properly" entail? what does it give you? Commented Sep 11, 2017 at 9:47
  • Is it really that hard to employ a search engine with a "remove item from list in python" query? Commented Sep 11, 2017 at 9:48
  • 1) What have you tried? 2) Does order matter? Commented Sep 11, 2017 at 9:49
  • [x for x in listobj if any(y is not Alba for y in x)] i think this is not proper one Commented Sep 11, 2017 at 9:51
  • 1
    @venkat It's certainly not proper. It won't even run. Commented Sep 11, 2017 at 9:51

4 Answers 4

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

or

list_of_tuples.pop(list_of_tuples.index(('Alba', 'Texas'))) 
Sign up to request clarification or add additional context in comments.

1 Comment

note -- removing items from a list while iterating over it can cause problems, as it can change the index of the remaining items in the list and can lead to unexpected behavior. One way to avoid this problem is to create a new list containing only the elements that you want to keep, rather than modifying the original list.
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")] 

Comments

3

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.

Comments

3

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())) 

1 Comment

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()))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.