Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 833
林侑萱 Avatar asked Dec 02 '25 05:12

林侑萱


1 Answers

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)
like image 155
Austin Avatar answered Dec 04 '25 13:12

Austin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!