0

While trying to remove a list from another list, I m facing the below issue.

element = [['(4.00,4.00)', '(4.00,2.00)'], ['(4.00,4.00)', '(4.00,8.00)'], ['(4.00,4.00)', '(2.00,2.00)'], ['(4.00,4.00)', '(5.00,5.00)']]
toremove = ['(4.00,4.00)', '(4.00,2.00)']

for j in element:
    if j == toremove:
            element = element.remove(toremove)
            print "element",element

Output that i get is None. "element None". Can anyone tell me what goes wrong here.

  • 1
    `remove` doesn’t return anything. Also changing the length of a list while iterating over it isn’t a smart move. – jonrsharpe Oct 04 '17 at 21:34
  • Ok got it! Can you explain what will possibly go wrong when we change length of the list while iterating? @jonrsharpe – buddingengineer Oct 04 '17 at 21:39
  • 1
    Possible duplicate of [How can I remove all instances of an element from a list in Python?](https://stackoverflow.com/questions/2186656/how-can-i-remove-all-instances-of-an-element-from-a-list-in-python) – HFBrowning Oct 04 '17 at 21:40
  • 1
    Also here's an example of someone having a problem when they tried to modify and iterate through a list at the same time: https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list – HFBrowning Oct 04 '17 at 21:47

1 Answers1

1
element=list(filter(lambda x: x!=toremove, element))

explanation:

lambda x: x!=toremove

lambda runs the logic in place which is written after : , and run its with variable provided in front of lambda i.e. x here.

filter(function to identify the element to be removed, list from which element to be removed)

filter returns a filter object that can be converted to list with list()

Nitesh chauhan
  • 316
  • 2
  • 5