林侑萱
林侑萱

Reputation: 37

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

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

Upvotes: 2

Views: 10961

Answers (5)

SV-97
SV-97

Reputation: 431

I don't know why everyone suggests loops. Imo the pythonic way would be the following:

total = sum([int(x) for x in a])

May be a bit heavier on RAM as compared to the total +=... with for loop approach but I'd wager it's faster.

EDIT: As @tevemadar pointed out you can actually do:

total = sum((int(x) for x in a))

which changes the list comprehension to be a generator that you then sum, which is a better solution as it does away with having to have the list in memory as one.

EDIT2: A thing to watch out for with the second solution is that changing a after defining total actually influences total.

Upvotes: 2

Austin
Austin

Reputation: 26037

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)

Upvotes: 10

Joe Iddon
Joe Iddon

Reputation: 20434

The str and int data types are immutable, so functions called on them can never modify their values.

Hence the int() function can't modify your i variable in the for-loop nor is it supposed to.

As a result, the int() function is designed to return a new integer, thus you must assign it somewhere or it will be "lost in the void".

I.e.

a = ['1', '2', '3']
total = 0
for i in a:
    total = total + int(i)

print(total)

Note that it is great practice to learn these, albeit simple, algorithms for operations on lists, strings etc, but the sum() built-in function is there to be used if your in a rush!

a = ['1', '2', '3']
print(sum([int(i) for i in a]))

N.B. I have also used a list-comprehension here that you may not be familiar with; they are really useful, I suggest learning them.

Upvotes: 3

tevemadar
tevemadar

Reputation: 13225

(Implementing the comment)
int(i) returns the integer value, i remains being the string it was before.
You need total = total + int(i):

a = ['1','2','3']
total = 0
for i in a:
    total = total + int(i)

print(total) # output:6

Upvotes: 1

Biswadip Mandal
Biswadip Mandal

Reputation: 544

a = ['1','2','3']
total = 0
for i in a:
    total = total + int(i)

Upvotes: 2

Related Questions