Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if my list has only 2 specific elements that can be repeated?

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.
like image 339
npatel Avatar asked Dec 13 '22 11:12

npatel


1 Answers

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
like image 82
iz_ Avatar answered Mar 01 '23 22:03

iz_