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
test_list = [ 5 , 6 , "gfg" , 8 , ( 5 , 7 ), 'is' , 9 ]
print ( "The original list is : " + str (test_list))
res = 0
for ele in test_list:
try :
res + = int (ele)
except :
pass
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
test_list = [ 5 , 6 , "gfg" , 8 , ( 5 , 7 ), 'is' , 9 ]
print ( "The original list is : " + str (test_list))
res = sum ( filter ( lambda i: isinstance (i, int ), test_list))
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
test_list = [ 5 , 6 , "gfg" , 8 , ( 5 , 7 ), 'is' , 9 ]
print ( "The original list is : " + str (test_list))
res = 0
for ele in test_list:
if type (ele) is int :
res + = ele
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
test_list = [ 5 , 6 , "gfg" , 8 , ( 5 , 7 ), 'is' , 9 ]
print ( "The original list is : " + str (test_list))
res = 0
for i in test_list:
if isinstance (i, int ):
res + = i
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
test_list = [ 5 , 6 , "gfg" , 8 , ( 5 , 7 ), 'is' , 9 ]
print ( "The original list is : " + str (test_list))
int_list = [ele for ele in test_list if isinstance (ele, int )]
res = sum (int_list)
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:
- 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
test_list = [ 5 , 6 , "gfg" , 8 , ( 5 , 7 ), 'is' , 9 ]
print ( "The original list is : " + str (test_list))
int_list = [x for x in test_list if isinstance (x, int )]
arr = np.array(int_list)
res = np. sum (arr)
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
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 | 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 | 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 | Interval List Summation
There are numerous ways to initialize the list with the elements, but sometimes, its required to initialize the lists with the numbers in a sliced way and find its summation. This can be custom and hence knowledge of this can come handy. Letâs discuss certain ways in which this can be done. Method #
3 min read
Python - Integers String to Integer List
In this article, we will check How we can Convert an Integer String to an Integer List Using split() and map()Using split() and map() will allow us to split a string into individual elements and then apply a function to each element. [GFGTABS] Python s = "1 2 3 4 5" # Convert the string to
2 min read
Python | Adding K to each element in a list of integers
In Python, we often need to perform mathematical operations on each element. One such operation is adding a constant value, K, to every element in the list. In this article, we will explore several methods to add K to each element in a list. Using List ComprehensionList comprehension provides a conc
2 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 t
3 min read
Python | i^k Summation in list
Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of i^k of list in just one line. Letâs discuss cer
5 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
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
Python - Convert Number to List of Integers
We need to split a number into its individual digits and represent them as a list of integers. For instance, the number 12345 can be converted to the list [1, 2, 3, 4, 5]. Let's discuss several methods to achieve this conversion. Using map() and str() Combination of str() and map() is a straightforw
3 min read