3

Consider the array a= [1, 2, 3, 1, 2, 3]. Now suppose I want to remove all the 2s in this array in python. So I apply a.remove(2). However the result which comes out is [1, 3, 1, 2, 3], i.e the only first 2 is removed. How can I remove all the 2s which appear in an array? In general, given an array and an element p, how can I remove all the elements of the array which are equal to p?

Edit:- I think I should mention this, this question has been inspired from a Brilliant computer science problem.

5
  • you can use list(set(myarray)) but it will rearrange the array so that it is in alphabetical/numerical order. Commented Jul 22, 2013 at 11:33
  • @The-IT I don't see how that is relevant to my question. Commented Jul 22, 2013 at 11:43
  • 1
    If you do that, you will find that all duplicates in the new list will be removed. list(set([2, 6, 3, 4, 5, 3, 5, 6, 5])) [2, 3, 4, 5, 6] Commented Jul 22, 2013 at 11:52
  • @The-IT Thank you! I did not think of it that way. :) Commented Jul 22, 2013 at 12:02
  • Yeh, I just reread my comment and realized it was worded really badly. My bad. Sorry. Commented Jul 22, 2013 at 12:07

2 Answers 2

4

Use a list comprehension to build a replacement list, where all elements are not equal to p:

a = [i for i in a if i != p]

Note that in Python, the datatype is called a list, not an array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works! I am just a beginner to python, and I am more used to java, that's why I used the word 'array' instead of 'list'.
3

You can use filter().

>>> a= [1, 2, 3, 1, 2, 3]
>>> filter(lambda x: x != 2, a)
[1, 3, 1, 3]

In a function :

>>> def removeAll(inList, num):
        return filter(lambda elem: elem != num, inList)

>>> removeAll(a, 2)
[1, 3, 1, 3]

5 Comments

Just a comment: afaik filter, map etc. return iterators in python 3. But correct me if I'm wrong…
List Comprehensions are more readable (although map may be a bit faster in some cases), but I just wanted to provide an alternative functional approach to the problem.
Yes of course, alternatives are great! It was just a comment. I edited it btw. (I meant those builtins don't behave the same in future python versions).
Can you please explain what is the function of the command 'lambda' here? Thanks for contributing, but a much simpler answer has already been posted. Anyways, I prefer remembering the alternatives. Thanks!
This link should be helpful - secnetix.de/olli/Python/lambda_functions.hawk

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.