Remove element from a list by key and by value

4

I have the following list

my_list = [1,2,3,4,5,6,7,8,9]

Let's say I want to remove num 7, by value and / or key, and stick with:

my_list = [1,2,3,4,5,6,8,9]

How do I do it?

    
asked by anonymous 21.06.2016 / 12:01

3 answers

4
my_list = [1,2,3,4,5,6,7,8,9]
val_remove = 7

Remove by value

my_list.remove(val_remove)

Note that this way:

  • It only removes the first occurrence of the element, if there are two or more val_remove (7, in this case) it will only remove the first one to find
  • If the value does not exist in the list it will throw an exception, if it does not capture it, it is:
  

ValueError: list.remove (x): x not in list

To remove only the first occurrence, without being sure if the element exists within the list:

if(val_remove in my_list):
    my_list.remove(val_remove)

To remove all occurrences of val_remove (7, in this case):

while val_remove in my_list:
    my_list.remove(val_remove)

With filter () and lambda :

If you are python 2.x, to achieve the same (remove all occurrences) you can:

filter(lambda a: a != val_remove, my_list)

If you are python 3.x, to reach it (remove all occurrences) you can:

list(filter(lambda a: a != val_remove, my_list))

Remove by key

Obviously you need to know the index of the value you want to remove beforehand, in this case it is 6, so we do:

del my_list[6]

If index (key) does not exist an exception is thrown:

  

IndexError: list assignment index out of range

If you are not sure that the index exists in my_list you can also:

my_list = [i for i in my_list if my_list.index(i) != 6] # caso o index (chave) de i for 6 nao e copiado

Note that this last solution is not good to remove, it is more to copy the list to the same variable without the value that was in the index of val_remove (key of 7, is to 6, in this case)

    
21.06.2016 / 12:17
1

remove all desired occurrences 1 + x ...

def remove_item(my_list,*args):
    deletar = list(args)
    for item in deletar:
        while item in my_list:
            my_list.remove(item)
    return my_list

my_list = [1,2,3,4,5,6,2,7,8,1,1,100,4]
remove_item(my_list,1,4)
#[2, 3, 5, 6, 2, 7, 8, 100]
my_list = [1,2,3,"erro",4,5,6,2,7,8,1,1,100,4,"erro","PYTHON"]
remove_item(my_list,"erro",100,1)
#[2, 3, 5, 6, 2, 7, 8, 'PYTHON']
    
21.06.2016 / 17:00
1

Simple, to remove elements from a list by their value, simply use the remove method:

>>> my_list = [1,2,3,4,5,6,7,8,9]
>>> my_list.remove(7)
>>> my_list
[1, 2, 3, 4, 5, 6, 8, 9]

Now, to remove some element from a list by its index, you can use the pop method:

>>> my_list = [1,2,3,4,5,6,7,8,9]
>>> my_list.pop(6)
7
>>> my_list
[1, 2, 3, 4, 5, 6, 8, 9]

See more about working with python lists at official documentation .

    
21.06.2016 / 12:17