Python | Summation of integers in heterogeneous list

Sometimes, while working with Python, we can come across a problem in which we require to find the sum of list. This problem is easier to solve. But this can get complex in case we have mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using Type casting + Exception Handling 
We can employ a brute force method to type caste each element and catch the exception if any occurs. This can ensure that only integers are added to sum and hence can solve the problem.
Python3
| # Python3 code to demonstrate working of# Summation of integers in heterogeneous list# using type caste and exception handling# initializing listtest_list =[5, 6, "gfg", 8, (5, 7), 'is', 9]# printing original listprint("The original list is : "+str(test_list))# Summation of integers in heterogeneous list# using type caste and exception handlingres =0forele intest_list:    try:        res +=int(ele)    except:        pass# printing result print("Summation of integers in list : "+str(res)) | 
The original list is : [5, 6, 'gfg', 8, (5, 7), 'is', 9] Summation of integers in list : 28
Time Complexity: O(n) where n is the number of elements in the list “res_list”.  
Auxiliary Space: O(1), where n is the number of elements in the new res list 
Method #2 : Using sum() + isinstance() 
This problem can also be solved using the inbuilt function of sum() and it also supports the instance filter using isinstance() which can be feeded with integer and hence solve the problem.
Python3
| # Python3 code to demonstrate working of# Summation of integers in heterogeneous list# using sum() + isinstance()# initializing listtest_list =[5, 6, "gfg", 8, (5, 7), 'is', 9]# printing original listprint("The original list is : "+str(test_list))# Summation of integers in heterogeneous list# using sum() + isinstance()res =sum(filter(lambdai: isinstance(i, int), test_list))# printing result print("Summation of integers in list : "+str(res)) | 
The original list is : [5, 6, 'gfg', 8, (5, 7), 'is', 9] Summation of integers in list : 28
Time Complexity: O(n) where n is the number of elements in the list “test_list”. Using sum() + isinstance() performs n number of operations.
Auxiliary Space: O(1), constant space required
Method #3 : Using type() method
Python3
| # Python3 code to demonstrate working of# Summation of integers in heterogeneous list# initializing listtest_list =[5, 6, "gfg", 8, (5, 7), 'is', 9]# printing original listprint("The original list is : "+str(test_list))# Summation of integers in heterogeneous list# using type caste and exception handlingres =0forele intest_list:    iftype(ele) isint:        res+=ele# printing resultprint("Summation of integers in list : "+str(res)) | 
The original list is : [5, 6, 'gfg', 8, (5, 7), 'is', 9] Summation of integers in list : 28
Time Complexity : O(N)
Auxiliary Space : O(N)
Method 4: Using for loop
We first initialize the list and print it. Then, we define a variable res to store the sum of integers in the list. We use a loop to iterate over each element of the list and check if it is an integer using the isinstance() function. If it is an integer, we add it to res. Finally, we print the sum of integers in the list.
Below is the implementation:
Python3
| # Python3 code to demonstrate working of# Summation of integers in heterogeneous list# using loop# initializing listtest_list =[5, 6, "gfg", 8, (5, 7), 'is', 9]# printing original listprint("The original list is : "+str(test_list))# Summation of integers in heterogeneous list# using loopres =0fori intest_list:    ifisinstance(i, int):        res +=i# printing resultprint("Summation of integers in list : "+str(res)) | 
The original list is : [5, 6, 'gfg', 8, (5, 7), 'is', 9] Summation of integers in list : 28
Time complexity: O(n), where n is the length of the input list. This is because the loop iterates over each element of the list once, and the time taken for each iteration is constant.
Auxiliary space: O(1), which is constant. 
Method #5: Using List Comprehension
Use list comprehension to filter out non-integer elements from the list and then sum the remaining integers.
Step-by-step approach:
- Initialize the list test_list.
- Use list comprehension to filter out non-integer elements from the list and create a new list of integers only.
- Use the sum() function to add up the integers in the new list.
- Print the result.
Below is the implementation of the above approach:
Python3
| # Python3 code to demonstrate working of# Summation of integers in heterogeneous list# using list comprehension# initializing listtest_list =[5, 6, "gfg", 8, (5, 7), 'is', 9]# printing original listprint("The original list is : "+str(test_list))# Summation of integers in heterogeneous list# using list comprehensionint_list =[ele forele intest_list ifisinstance(ele, int)]res =sum(int_list)# printing result print("Summation of integers in list : "+str(res)) | 
The original list is : [5, 6, 'gfg', 8, (5, 7), 'is', 9] Summation of integers in list : 28
Time complexity: O(n) where n is the number of elements in the list.
Auxiliary space: O(k) where k is the number of integer elements in the list.
Method #6: Using numpy:
- Initialize the input list test_list.
- Print the original list.
- Initialize the variable res to 0 to store the sum of integers in the list.
- Iterate over each element ele in test_list.
- Check if the type of ele is int using the type() function.
- If the type of ele is int, add it to res.
- After iterating over all elements, print the sum of integers in the list.
- (Optional) If using numpy, convert the list to a numpy array.
- (Optional) Use numpy functions to filter out non-integer elements and sum the array.
- (Optional) Print the sum of integers in the list.
Python3
| importnumpy as np# initializing listtest_list =[5, 6, "gfg", 8, (5, 7), 'is', 9]# printing original listprint("The original list is : "+str(test_list))# filter out non-integer elementsint_list =[x forx intest_list ifisinstance(x, int)]# convert list to numpy arrayarr =np.array(int_list)# use numpy.sum() to get the sum of the arrayres =np.sum(arr)# print resultprint("Summation of integers in list : "+str(res))#This code is contributed by Rayudu. | 
Output: The original list is : [5, 6, 'gfg', 8, (5, 7), 'is', 9] Summation of integers in list : 28
The time complexity : O(n), where n is the number of elements in the list, since the algorithm iterates over each element of the list once.
The auxiliary space :O(1), since only a few variables are used to store the sum and iterate over the list, and their memory requirements do not depend on the size of the input list.
 
				 
					


