Sum of list (with string types) in Python

In Python, type of behavior will not change for data type. Below example is list containing integer type in, we have to take all int type numbers from list even it is declared in string.


Input : list1 = [12, 'geek', 2, '41', 'for', 10, '8', 6, 4, 'geeks', 7, '10']
Output : 100

Input : list1 = [100, 'geek', 200, '400', 'for', 101, '2018', 
                               64, 74, 'geeks', 27, '7810']
Output :10794

We use type() in Python and isdigit() in Python to achieve this.





# Python program to find sum of list with different
# types.
def calsum(l):
    # returning sum of list using List comprehension
    return  sum([int(i) for i in l if type(i)== int or i.isdigit()])
# Declaring list
list1 = [12, 'geek', 2, '41', 'for', 10, '8', 6, 4, 'geeks', 7, '10']
list2 = [100, 'geek', 200, '400', 'for', 101, '2018', 64, 74, 'geeks', 27, '7810']
# Result of sum of list
print calsum(list1)
print calsum(list2)


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.