Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my list is not being converted to a float

Hello guys I have the list of [0.5, 1.5, 2.5, 3.5]

def calc_mean(arglist):
  return sum(arglist)/len(arglist)
print(calc_mean([0.5, 1.5, 2.5, 3.5]))

And then the same list but the elements are strings [‘0.5′,’1.5′,’2.5′,’3.5’] and I need to convert them to floats and then calculate the average but I’m getting the error (unsupported operand type(s) for +: ‘int’ and ‘str’) because the line return sum(arglist)/len(arglist) is working with integers and strlist is a string why strlist isn’t being converted to a float and it’s being treated as a str even though I converted it using [float(i) if ‘.’ in i else int(i) for i in strlist]

def str2float(strlist):
  flist = [float(i) if '.' in i else int(i) for i in strlist] 
  return flist
strlist =  ['0.5','1.5','2.5','3.5']
print(str2float(strlist))
print(calc_mean(strlist))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

print(calc_mean(strlist))

As noted in comments, you have not converted strlist before passing it to calc_mean.

print(calc_mean(str2float(strlist)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading