How to remove specific element from an array using python


I want to write something that removes a specific element from an array. I know that I have to for loop through the array to find the element that matches the content.

Let's say that I have an array of emails and I want to get rid of the element that matches some email string.

I'd actually like to use the for loop structure because I need to use the same index for other arrays as well.

Here is the code that I have:

for index, item in emails:
    if emails[index] == '':
12/2/2018 3:26:26 AM

Accepted Answer

You don't need to iterate the array. Just:

>>> x = ['', '']
>>> x
['', '']
>>> x.remove('')
>>> x

This will remove the first occurence that matches the string.

EDIT: After your edit, you still don't need to iterate over. Just do:

index = initial_list.index(item1)
del initial_list[index]
del other_list[index]
5/14/2018 2:52:56 PM

Using filter() and lambda would provide a neat and terse method of removing unwanted values:

newEmails = list(filter(lambda x : x != '', emails))

This does not modify emails. It creates the new list newEmails containing only elements for which the anonymous function returned True.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow