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.
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)]
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"]))