Sai Sai - 4 months ago 9
Python Question

Round off numbers in python

I have a list of numbers [0,10,20,30,40,50] now this list will be appended by random numbers such as 33 ,43,I have to check the list every time it appends no to the list and i want them to be rounded off to 30 and 40.

Answer

Use the round() built-in function. In conjuction with a list comprehension, can give us an expressive one-line function!

def round_list(l):
    return [int(round(i, -1)) for i in l]

Sample output:

l = [24, 34, 41, 40, 12, 434, 53, 53]
print round_list(l)
>>> [20, 30, 40, 40, 10, 430, 50, 50]
Comments