Remove a list inside a list
10,432
Will remove ALL inner lists:
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
cleaned = [item for item in messy_list if not isinstance(item,list)]
print(cleaned)
I am using a list comprehension that inspects all item
s of your messy_list
and only adds it to the resulting new list if it is not a list itself.
Author by
Jake
Updated on June 26, 2022Comments
-
Jake almost 2 years
I want to remove the list [1,2,3] inside the outer list. I tried
or isinstance(item, list)
but that didn't work, the nested list was still there.messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] # Your code goes below here messy_list.pop(3) messy_list.insert(0,1) for item in messy_list: if isinstance(item, str) or isinstance(item, bool): messy_list.remove(item) messy_list.pop(-1) print(messy_list)
I would like to know if there wasn't a better way to check if there's a list inside the list, and then remove from the outer list, instead of having to hardcode it with .pop(-1)