To determine whether a given list in Python only contains other lists, you can utilize Python’s built-in all() function in combination with isinstance(). This approach ensures that every element in the list is a list, without recursively checking the contents of those inner lists.
✅ Solution Overview
You can use a generator expression inside the all() function to iterate through each element of the list and check if it is an instance of list.
Here's the concise and efficient implementation:
python
def contains_only_lists(lst):
return all(isinstance(item, list) for item in lst)
🔍 Explanation
isinstance(item, list) checks whether item is an instance of the list type.
all(...) ensures that all items in the generator expression satisfy this condition.
The generator expression is lazy-evaluated, meaning it stops checking as soon as it finds a non-list element, making it efficient.
🧪 Example Usage
python
# All elements are lists
print(contains_only_lists([[1, 2], [3], []])) # Output: True
# One element is not a list (integer)
print(contains_only_lists([1, [2, 3], [4]])) # Output: False
# Empty list is technically valid (no non-list elements)
print(contains_only_lists([])) # Output: True
# List containing a tuple (not a list)
print(contains_only_lists([(), [1], [2]])) # Output: False
# List containing itself (recursive structure)
a = []
a.append(a)
print(contains_only_lists(a)) # Output: True (only checks top-level elements)
⚠️ Notes
Subclasses of list will also return True due to isinstance(). If you want to strictly check for built-in list type, use type(item) is list instead.
This function assumes the input is already a list. If you're unsure, you can add a preliminary check:
python
def contains_only_lists(lst):
if not isinstance(lst, list):
return False
return all(isinstance(item, list) for item in lst)
✅ Summary
To check if a list only contains other lists, use:
python
all(isinstance(item, list) for item in lst)
This is a clean, Pythonic, and efficient way to validate the structure of a list at the top level.