Python | Summation of integers in heterogeneous list
Last Updated :
02 May, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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
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.
Similar Reads
Python | Alternate element summation in list The problem of getting summation of a list is quite generic and we might some day face the issue of getting the summation of alternate elements and get the list of 2 elements containing summation of alternate elements. Let's discuss certain ways in which this can be performed. Method #1 : Using list
5 min read
Python | Pair summation of list elements Sometimes, while working with Python list, one can have a problem in which one needs to find perform the summation of list in pair form. This is useful as a subproblem solution of bigger problem in web development and day-day programming. Let's discuss certain ways in which this problem can be solve
4 min read
Python program to find sum of elements in list Finding the sum of elements in a list means adding all the values together to get a single total. For example, given a list like [10, 20, 30, 40, 50], you might want to calculate the total sum, which is 150. Let's explore these different methods to do this efficiently.Using sum()sum() function is th
3 min read
Find Sum and Average of List in Python Our goal is to find sum and average of List in Python. The simplest way to do is by using a built-in method sum() and len(). For example, list of numbers is, [10, 20, 30, 40, 50] the sum is the total of all these numbers and the average is the sum divided by the number of elements in the list.Using
2 min read
Element indices Summation - Python Our task is to calculate the sum of elements at specific indices in a list. This means selecting elements at specific positions and computing their sum. Given a list and a set of indices, the goal is to compute the sum of elements present at those indices. For example, given the list [10, 20, 30, 40
3 min read
Python | Grouped summation of tuple list Many times, we are given a list of tuples and we need to group its keys and perform certain operations while grouping. The most common operation is addition. Let's discuss certain ways in which this task can be performed. Apart from addition, other operations can also be performed by doing small cha
10 min read