how should I convert string to integer and sum the list?

  • A+

I want to sum up the list of string. I tried to convert strings to integers by using for loop and int(). But it didn't work. What should I do? Thank you for your answer!

a = ['1','2','3'] total = 0 for i in a:     int(i)     total = total + i  print(total) #expected output:6 


Use sum() with map() to map each item to int:

a = ['1','2','3']  print(sum(map(int, a))) # 6 

int(i) as such does not alter i unless you assign it back. So your code should be:

for i in a:     i = int(i)     total = total + i 

Or, shortly:

for i in a:     total = total + int(i) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: