Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element in list using list comprehension - Python

I have a list like this:

['A','B','C']

What I need is to remove one element based on the input I got in the function. For example, if I decide to remove A it should return:

['B','C']

I tried with no success

list = ['A','B','C']
[var for var in list if list[var] != 'A']

How can I do it? Thanks

like image 342
The Condor Avatar asked May 07 '14 11:05

The Condor


People also ask

How to remove items from a list in Python?

del is a powerful tool in Python which is used to remove entire objects. It can also be used to remove elements from a given list. Some of the observations derived from the above script are: del is not a method. It is a statement that deletes the item placed after it.

How do I remove an element from a list?

Just do list.remove ('A') and it will be removed. If you have the index of the item to be removed, use the pop method. list.pop (0). If you not sure whether the element exists or not, you might want to check before you delete: list1 = [12,24,35,24,88,120,155] while 24 in list1: list1.remove (24) print (list1)

How to remove a range of elements from a list python?

Python has a provision of removing a range of elements from a list. This can be done by del statement. To remove multiple elements from a list in a sequence, we need to provide a range of elements to the del statement. A range of elements take a starting index and/or an ending index, separated by a colon ':'.

What is a list in Python?

Python lists are the most basic data structure used in day-to-day programming. We come across situations where we need to remove elements from lists and in this article, we’ll discuss exactly that.


2 Answers

The improvement to your code (which is almost correct) would be:

list = ['A','B','C']
[var for var in list if var != 'A']

However, @frostnational's approach is better for single values.

If you are going to have a list of values to disallow, you can do that as:

list = ['A','B','C', 'D']
not_allowed = ['A', 'B']
[var for var in list if var not in not_allowed]
like image 29
sshashank124 Avatar answered Sep 22 '22 11:09

sshashank124


Simple lst.remove('A') will work:

>>> lst = ['A','B','C']
>>> lst.remove('A')
['B', 'C']

However, one call to .remove only removes the first occurrence of 'A' in a list. To remove all 'A' values you can use a loop:

for x in range(lst.count('A')):
    lst.remove('A')

If you insist on using list comprehension you can use

>>> [x for x in lst if x != 'A']
['B', 'C']

The above will remove all elements equal to 'A'.

like image 142
vaultah Avatar answered Sep 20 '22 11:09

vaultah