Open In App

Python | Summation of integers in heterogeneous list

Improve
Improve
Like Article
Like
Save
Share
Report

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 list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Summation of integers in heterogeneous list
# using type caste and exception handling
res = 0
for ele in test_list:
    try:
        res += int(ele)
    except :
        pass
 
# printing result
print("Summation of integers in list : " + str(res))


Output : 

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 list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Summation of integers in heterogeneous list
# using sum() + isinstance()
res = sum(filter(lambda i: isinstance(i, int), test_list))
 
# printing result
print("Summation of integers in list : " + str(res))


Output : 

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 list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Summation of integers in heterogeneous list
# using type caste and exception handling
res = 0
for ele in test_list:
    if type(ele) is int:
        res+=ele
 
# printing result
print("Summation of integers in list : " + str(res))


Output

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 list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Summation of integers in heterogeneous list
# using loop
res = 0
for i in test_list:
    if isinstance(i, int):
        res += i
 
# printing result
print("Summation of integers in list : " + str(res))


Output

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 list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Summation of integers in heterogeneous list
# using list comprehension
int_list = [ele for ele in test_list if isinstance(ele, int)]
res = sum(int_list)
 
# printing result
print("Summation of integers in list : " + str(res))


Output

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:

  1. Initialize the input list test_list.
  2. Print the original list.
  3. Initialize the variable res to 0 to store the sum of integers in the list.
  4. Iterate over each element ele in test_list.
  5. Check if the type of ele is int using the type() function.
  6. If the type of ele is int, add it to res.
  7. After iterating over all elements, print the sum of integers in the list.
  8. (Optional) If using numpy, convert the list to a numpy array.
  9. (Optional) Use numpy functions to filter out non-integer elements and sum the array.
  10. (Optional) Print the sum of integers in the list.

Python3




import numpy as np
 
# initializing list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# filter out non-integer elements
int_list = [x for x in test_list if isinstance(x, int)]
 
# convert list to numpy array
arr = np.array(int_list)
 
# use numpy.sum() to get the sum of the array
res = np.sum(arr)
 
# print result
print("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.



Last Updated : 02 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads