2

My code will not delete the items if they exist in the list.

This is the list I am working with: [1, 2, 3, 4, 5, 6, 7, 8]

Run the function: remove_items_from_list(my_list, [1,5,6])

This is the OUTPUT I am expecting: [2, 3, 4, 7, 8]

But I am getting: [1, 2, 3, 4, 5, 6, 7, 8]

def remove_items_from_list(ordered_list, items_to_remove):
    if [items_to_remove] in ordered_list :
        ordered_list.remove([items_to_remove])
    return ordered_list

These are my instructions: This function takes two arguments: a list, and a list of numbers to remove from the list. This function will then check if those items exist within that list, and if they exist, then they will be removed.

Marius Mucenicu
  • 1,685
  • 2
  • 16
  • 25
Here2Learn
  • 33
  • 1
  • 5

3 Answers3

3

if [items] in list checks that: a list containing the list of items is an element of the list. That is, you are asking: is [[1, 2, 3]] a member of the list? Probably not.

What you want to do is iterate over the element of items_to_remove and do what you did

for item in items_to_remove:
    if item in list:
        list.remove(item)
blue_note
  • 27,712
  • 9
  • 72
  • 90
2

Try this :

def remove_items_from_list(ordered_list, items_to_remove):
    return [i for i in ordered_list if not i in items_to_remove]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
  • your function does not what was asked and does not what it describes in the function name. it does not manipulate a list, it returns a new list. – Bastian Oct 02 '19 at 14:40
1

The answer blue_note provided is correct, but a more idiomatic approach would be to do it with a list comprehension, like so:

return [x for x in ordered_list if x not in items_to_remove]

Note that this will not remove the items from the original list, but return a new list without the items (as pointed out by Bastian).

EDIT: Arkistarvh Kltzuonstev beat me to it, but I would still argue that x not in y is more idiomatic that not x in y.

sjp
  • 382
  • 4
  • 15
  • it is not the same... the question was to remove items from a list, but you return a new list. depending on where it is used it might break code. – Bastian Oct 02 '19 at 14:39
  • Considering that the OP presented a function that takes a list, removes items from it and returns the same list, I am assuming this is what he actually wants. If it is important that items should be removed from the initial list, the function should not have a return value (for the sake of clarity). – sjp Oct 02 '19 at 14:42
  • Your point is still valid, though, so I have clarified my answer. – sjp Oct 02 '19 at 14:44
  • please read what he wrote in his instructions, not assume from his not working code ... the instructions clearly says that the items should be removed from the list – Bastian Oct 02 '19 at 14:45