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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With