Sue_ka
Sue_ka

Reputation: 31

checking list of floats for an integer

I have a list of float numbers like below: I know they are float because I typecasted them, while taking them as input.

A = [1.0, 3.0, 3.5, 5.0]

I need to check this list for integers, something like

if any(elements of the list is not an integer):

then do something

I am still new to python and I would like to know what is the most compact way of doing this.

Upvotes: 0

Views: 764

Answers (1)

Amadan
Amadan

Reputation: 198344

"If not all elements of A are integral":

if not all(x.is_integer() for x in A):

or equivalently, using your phrasing (at the cost of N not operations instead of one):

if any(not x.is_integer() for x in A):

While it is quite legible (basically English), to understand how to write it yourself, you need to first know about list comprehensions, then understand generator expressions. You will also need any and float.is_integer.

Upvotes: 3

Related Questions