Skip to content
Related Articles

Related Articles

Sum of list (with string types) in Python
  • Last Updated : 04 Dec, 2020

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

Examples:

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))

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :