How To Check If All Elements In A List Are Whole Numbers
If I have a list such as : List = [12,6,3,5,1.2,5.5] Is there a way I can check if all the numbers are whole numbers? I tried something like def isWhole(d): if (d%1 == 0 ) : fo
Solution 1:
So you want integers and floats that are equal to integers?
def is_whole(d):
"""Whether or not d is a whole number."""
return isinstance(d, int) or (isinstance(d, float) and d.is_integer())
In use:
>>> for test in (1, 1.0, 1.1, "1"):
print(repr(test), is_whole(test))
1 True # integer
1.0 True # float equal to integer
1.1 False # float not equal to integer
'1' False # neither integer nor float
You can then apply this to your list with all
and map
:
if all(map(is_whole, List)):
or a generator expression:
if all(is_whole(d) for d in List):
Solution 2:
Simple solution for a list L:
def isWhole(L):
for i in L:
if i%1 != 0:
return False
return True
Solution 3:
List = [12,6,3,5,1.2,5.5]
for i in List:
if i%1 != 0 :
print(False)
break
Post a Comment for "How To Check If All Elements In A List Are Whole Numbers"