locoboy locoboy - 28 days ago 14
Python Question

How to remove specific element in an array using python

I'm new to Python and want to write something that removes a specific element in an array. I know that I have to

for
loop through the array to find the element that matches the content, but Python for loops are a bit funny.

lets 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] == 'something@something.com':
emails.pop(index)
otherarray.pop(index)

Answer

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

>>> x = ['ala@ala.com', 'bala@bala.com']
>>> x
['ala@ala.com', 'bala@bala.com']
>>> x.remove('ala@ala.com')
>>> x
['bala@bala.com']

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)
initial_list.remove(item1)
other_list.remove(other_list[index])