I want to compute the sum of all elements of a list, but the elements are text. E.g. ['1','0','1']. How can I change the data type of all elements to 'int' so that I can apply *sum() *function.?

0 votes

There can be several ways to change the data type of list elements. You can try the following two one-liner pythonic approaches:

>>> a=['aa','1','0','1']

>>> map(int,a[1:])

[1, 0, 1]

>>> [int(s) for s in a[1:]]

[1, 0, 1]

To compute the sum of the list items, you can do one of the followings:

>>> sum(map(int,a[1:]))

2

>>> sum([int(s) for s in a[1:]])

2