0

Q. Write a function

remove(data, value)

that returns a new list that contains the same elements as the list data except for those that equal value. Use a list comprehension. Your function should remove all items equal to value. For example, remove([3, 1, 5, 3, 9], 3) should return the list [1, 5, 9].

Down below is what I worked on, but it returns None.

def remove (data,value):
    ans = [ data.remove(value) for ele in data if value == ele ]
    return ans

assert(remove([3,1,5,3,9], 1) ==[3,5,3,9])

These should work for this function. Please let me know what should I do ??

wjandrea
  • 28,235
  • 9
  • 60
  • 81
hursooo
  • 43
  • 5
  • 3
    Why do you think it returns `[None]`? What does `data.remove()` return? What's the point of modifying `data` if you're returning `ans`? – wjandrea Aug 27 '20 at 02:40
  • Please [edit] the question to have a descriptive title. BTW welcome to SO! Check out the [tour] and [ask]. It would help if you provided the actual output in the question itself. See [mre] for reference. – wjandrea Aug 27 '20 at 02:42
  • Hint, `data.remove` *modifies `data` and returns `None`* – juanpa.arrivillaga Aug 27 '20 at 02:42
  • 1
    Does this answer your question? [Remove all occurrences of a value from a list?](https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list) Specifically [this answer](https://stackoverflow.com/a/1157132/4518341) – wjandrea Aug 27 '20 at 02:45

3 Answers3

0

you cannot remove elements in a list while you're iterating over it. create a new list and keep all elements except the ones that match ele.

def remove(data, value):
    ans = [ele for ele in data if value != ele]
    return ans
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    *"you cannot remove elements in a list while you're iterating over it"* - You can actually, but it might cause unexpected results. – wjandrea Aug 27 '20 at 02:50
  • BTW welcome to SO! Check out the [tour], and [answer] if you want advice. – wjandrea Aug 27 '20 at 02:50
0

This is a duplicate of Remove all occurrences of a value from a list? however, I don't think your case of the issue is well-explained.

There are a few clear issues which are seen in the comments, but not clearly Answering the Question.

  • .remove() method of lists will remove the first instance of its argument and then return None
  • you both change the original list and create a new list, while you would be better served by only doing one as-detailed by numerous answers in the duplicate question!
ti7
  • 16,375
  • 6
  • 40
  • 68
-1
def remove(data, value):
   return [i for i in data if i != value]

This will iterate over everything properly.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
neuops
  • 342
  • 3
  • 16