Remove Empty Lists in Python

Remove empty sublists from a list of lists.

BeginnerList ProgramsExample 16 of 25
remove-empty-lists.py
Run in browser
1# Program to remove empty lists from a list
2
3items = eval(input("Enter a list of lists (e.g., [[], [1], [], [2, 3]]): "))
4
5filtered = [x for x in items if x]
6
7print("After removing empty lists:", filtered)

Output

Enter a list of lists (e.g., [[], [1], [], [2, 3]]): [[], [1], [], [2, 3]]
After removing empty lists: [[1], [2, 3]]

What's going on

An empty list is falsy, so we filter on truthiness to keep only non-empty lists.