In Python is there a way to turn 1.0 into a integer 1 while the same function ignores 1.5 and leaves it as a float?

Right now, int() will turn 1.0 into 1 but it will also round 1.5 down to 1, which is not what I want.

ANSWER

Using is_integer():

Example from the docs:

>>> (1.5).is_integer()
False
>>> (1.0).is_integer()
True
>>> (1.4142135623730951).is_integer()
False
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False

INPUT:

s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]

Hence:

print([int(x) if x.is_integer() else x for x in s])

Wrapped in a function:

def func(s):
    return [int(x) if x.is_integer() else x for x in s]

print(func(s))

If you do not want any import:

def func(s):
    return [int(x) if x == int(x) else x for x in s]

print(func(s))

Using map() with lambda function and the iter s:

print(list(map(lambda x: int(x) if x.is_integer() else x, s)))

OR

print(list(map(lambda x: int(x) if int(x) == x else x, s)))

OUTPUT:

[1.5, 1, 2.5, 3.54, 1, 4.4, 2]