I have [{"a":1,"b":2},{"stud1":"Sid","Age":12},[{},{},{},{}],[], {"a2":3,"b4":4},{}]
How I can remove this type of empty, list and empty list of dictionary of list by using python3.
I have tried
while {} in data:
data.remove({})
It just remove the {} not the empty lists
CodePudding user response:
Here's my code, it only works for one level of depth:
def is_empty(l):
# return's True if l is empty or if the contents are empty
if l is None or not l:
return True
return not all(v for v in l)
l = [{"a": 1, "b": 2}, {"stud1": "Sid", "Age": 12}, [{}, {}, {}, {}], [], {"a2": 3, "b4": 4}, {}]
l = [a for a in l if not is_empty(a)]
print(l)
Note: This code is using the fact the objects are true-fy, you can read about it.
output:
[{'a': 1, 'b': 2}, {'stud1': 'Sid', 'Age': 12}, {'a2': 3, 'b4': 4}]
CodePudding user response:
A little more archaic than @eilonlif's answer, but on a single line. It also makes some assumptions that you are trying to solve the specific list you mentioned, and doesnt address @Grismar's reasonable scenarios..
l = [{"a":1,"b":2},{"stud1":"Sid","Age":12},[{},{},{},{}],[], {"a2":3,"b4":4},{}]
print ([a for a in [x for x in l if x] if all(a)])
Result:
[{'a': 1, 'b': 2}, {'stud1': 'Sid', 'Age': 12}, {'a2': 3, 'b4': 4}]