0

need to write a recurive function to remove elements of list but keep the arrays in the result such as.

def remove_words(listx):
    for element in listx:
        if isinstance(element, list):
            remove_words(element)
        else:
            listx.remove(element)

    return listx

remove_words(["a", "b", ["c"]]) would return [[]]

My code returns ["b",[]] for some reason it's missing an element.

9
  • 2
    You remove an element of a list while iterating it. Do not do that. You remove the first element and when the index moves on, the new second element is the formerly third... find a way to avoid that! Commented Jan 9, 2018 at 9:46
  • You are removing element from list while iterating so just create a copy of list inside function and return that list Commented Jan 9, 2018 at 9:48
  • Do you want to modify your list in-place, or can you create a new list? Commented Jan 9, 2018 at 9:59
  • Can you provide a code example using this logic please? @tobias_k It doesn't matter, just needs to return proper nested lists. Commented Jan 9, 2018 at 10:03
  • Why did you specify a recursive solution? Mixing an iterative approach (for) with recursion is odd. If you want a recursive solution, this is not a very good start. Commented Jan 9, 2018 at 10:06

2 Answers 2

2

Do not remove elements from a collection while iterating it. Repeated calls to list.remove are also not ideal performance-wise since each removal (from a random index) is O(N). A simple way around both issues would be the following comprehension:

def remove_words(listx):
    return [remove_words(e) for e in listx if isinstance(e, list)]

The seemingly missing base case is a list with no nested lists where an empty list is returned.

If you want to modify the list in-place, you can use slice assignment:

def remove_words(listx):
    listx[:] = [remove_words(e) for e in listx if isinstance(e, list)]
Sign up to request clarification or add additional context in comments.

Comments

0
def remove_words(listx):
  if listx == []:
    return []
  elif not isinstance(listx[0], list):
    return remove_words(listx[1:])
  else:
    return [remove_words(listx[0])] + remove_words(listx[1:])

print(remove_words(["a", "b", ["c"]]))
print(remove_words(["a", ["b",["c","d"],"c"], [["f"],["g"]],"h"]))

Comments

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.