w3resource

Python: Remove empty lists from a given list of lists

Python List: Exercise - 141 with Solution

Remove Empty Lists from Nested List

Write a Python program to remove empty lists from a given list of lists.

Sample Solution:

Python Code:

# Create a list 'list1' that contains a mix of empty lists, strings, and sublists
list1 = [[], [], [], 'Red', 'Green', [1, 2], 'Blue', [], []]

# Print a message indicating the original list
print("Original list:")
# Print the contents of 'list1'
print(list1)

# Print a message indicating the operation to remove empty lists
print("\nAfter deleting the empty lists from the said lists of lists")

# Create a new list 'list2' containing non-empty elements from 'list1'
list2 = [x for x in list1 if x]

# Print 'list2', which contains non-empty elements
print(list2)

Sample Output:

Original list:
[[], [], [], 'Red', 'Green', [1, 2], 'Blue', [], []]

After deleting the empty lists from the said lists of lists
['Red', 'Green', [1, 2], 'Blue']

Flowchart:

Flowchart: Remove empty lists from a given list of lists.

Python Code Editor:

Previous: Write a Python program to remove the specific item from a given list of lists.
Next: Write a Python program to sum a specific column of a list in a given list of lists.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-141.php