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?
defis_whole(d):
"""Whether or not d is a whole number."""returnisinstance(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))
1True# integer 1.0True# float equal to integer1.1False# float not equal to integer'1'False# neither integer nor float
You can then apply this to your list with all
and map
:
ifall(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:
defisWhole(L):
for i in L:
if i%1 != 0:
returnFalsereturnTrue
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"