How to remove specific element from an array using python
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 How To Remove Specific Element From An Array Using Python
00:34 Accepted Answer Score 230
00:57 Answer 2 Score 4
01:21 Answer 3 Score 5
01:49 Answer 4 Score 24
02:07 Thank you
--
Full question
https://stackoverflow.com/questions/7118...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays
#avk47
ACCEPTED ANSWER
Score 230
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)
del initial_list[index]
del other_list[index]
ANSWER 2
Score 24
Using filter() and lambda would provide a neat and terse method of removing unwanted values:
newEmails = list(filter(lambda x : x != 'something@something.com', emails))
This does not modify emails. It creates the new list newEmails containing only elements for which the anonymous function returned True.
ANSWER 3
Score 5
Your for loop is not right, if you need the index in the for loop use:
for index, item in enumerate(emails):
# whatever (but you can't remove element while iterating)
In your case, Bogdan solution is ok, but your data structure choice is not so good. Having to maintain these two lists with data from one related to data from the other at same index is clumsy.
A list of tupple (email, otherdata) may be better, or a dict with email as key.
ANSWER 4
Score 4
The sane way to do this is to use zip() and a List Comprehension / Generator Expression:
filtered = (
(email, other)
for email, other in zip(emails, other_list)
if email == 'something@something.com')
new_emails, new_other_list = zip(*filtered)
Also, if your'e not using array.array() or numpy.array(), then most likely you are using [] or list(), which give you Lists, not Arrays. Not the same thing.