How can I check if my list has only 2 specific elements that can be repeated?
For example: Valid elements that I expect to be in my list are only 2:
1. abstract.f
2. None
If list has any other element, then it should throw an error message.
list1 = ['abstract.f', None, None, 'abstract.f']
# This is a valid list as it doesn't have any other element than 2 of above.
list1 = ['abstract.f', None, 'xyz']
# This is invalid list as it has 'xyz' which is not expected.
You can use all
to output a Boolean:
# Put items considered valid in this list
valid = ['abstract.f', None]
list1 = ['abstract.f', None, None, 'abstract.f']
print(all(el in valid for el in list1)) # True
list1 = ['abstract.f', None, 'xyz']
print(all(el in valid for el in list1)) # False
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