-2

I'm trying to convert a string list into a int list then add the elements.

Example:

convert test_list = ["1", "2", "5", "6"] to [1, 2, 5, 6] then add them to get 14.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Mrtophat
  • 9
  • 1

4 Answers4

4

You can use map

>>> test_list = ["1", "2", "5", "6"]
>>> map(int,test_list)
[1, 2, 5, 6]
>>> sum(map(int,test_list))
14

Other possible ways incude

  • sum([int(i) for i in test_list]) List Comp
  • sum(int(i) for i in test_list) Generator Expression

Note - map is a better alternative to list comp as mentioned here

map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
2

Using a list comprehension:

test_list = ["1", "2", "5", "6"]

new_list = [int(x) for x in test_list]

print sum(new_list)
MrAlexBailey
  • 5,219
  • 19
  • 30
0

The answers already posted are better practice however, a very easy to understand approach would be:

int_list = []
count = 0
for item in test_list:
    int_list.append(int(item))
    count += int(item)
print(count)
MapReduceFilter
  • 227
  • 2
  • 10
0

In my opinion it's the best solution:

test_list = ["1", "2", "5", "6"]
def sum_strings(X):
    """changes the type to int and adds elements"""
    return reduce(lambda x, y: int(x) + int(y), X)
print sum_strings(test_list)

Out:

14