How to check if all elements in a list are whole numbers
Question:
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 ) : for z in List return true.
That is obviously terribly wrong. What can I do?
Answers:
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):
Simple solution for a list L:
def isWhole(L):
for i in L:
if i%1 != 0:
return False
return True
List = [12,6,3,5,1.2,5.5]
for i in List:
if i%1 != 0 :
print(False)
break
if your list is lst = [12,6,3,5,1.2,5.5]
you can do this.
lst = [12,6,3,5,1.2,5.5]
print(all(isinstance(i,int) for i in lst))
it prints "True" if your list contains whole numbers, if not "False"
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 ) : for z in List return true.
That is obviously terribly wrong. What can I do?
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):
Simple solution for a list L:
def isWhole(L):
for i in L:
if i%1 != 0:
return False
return True
List = [12,6,3,5,1.2,5.5]
for i in List:
if i%1 != 0 :
print(False)
break
if your list is lst = [12,6,3,5,1.2,5.5]
you can do this.
lst = [12,6,3,5,1.2,5.5]
print(all(isinstance(i,int) for i in lst))
it prints "True" if your list contains whole numbers, if not "False"