I have a list with empty lists in it:
list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
How can I remove the empty lists so that I get:
list2 = ['text', 'text2', 'moreText']
I tried list.remove('') but that doesn't work.
Short answer: You can remove all empty lists from a list of lists by using the list comprehension statement [x for x in list if x] to filter the list.
In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.
Use the remove() Function to Remove All the Instances of an Element From a List in Python. The remove() function only removes the first occurrence of the element. If you want to remove all the occurrence of an element using the remove() function, you can use a loop either for loop or while loop.
Try
list2 = [x for x in list1 if x != []]
If you want to get rid of everything that is "falsy", e.g. empty strings, empty tuples, zeros, you could also use
list2 = [x for x in list1 if x]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With