Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sum of list (with string types) in Python
In this tutorial, we'll write a program that adds all numbers from a list containing mixed data types. The list may contain numbers in string or integer format, along with non-numeric strings.
Problem Statement
Given a list with mixed data types, we need to sum only the numeric values (both integers and numeric strings) while ignoring non-numeric strings ?
Input
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
Expected Output
4051
Solution Approach
Follow these steps to solve the problem:
- Initialize the list with mixed data types
- Initialize a variable total with 0
- Iterate over each element in the list
- Check if the element is numeric using two conditions:
- The element is an integer ? Check using
isinstance() - The element is a numeric string ? Check using
isdigit()method
- The element is an integer ? Check using
- Add the numeric element to the total
- Print the final sum
Implementation
# initializing the list
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
# initializing the variable total
total = 0
# iterating over the list
for element in random_list:
# checking whether it's a number or not
if isinstance(element, int) or (isinstance(element, str) and element.isdigit()):
# adding the element to the total
total += int(element)
# printing the total
print(total)
4051
How It Works
The program processes each element as follows:
-
1? Integer, add to total: 0 + 1 = 1 -
'10'? Numeric string, add to total: 1 + 10 = 11 -
'tutorialspoint'? Non-numeric string, skip -
'2020'? Numeric string, add to total: 11 + 2020 = 2031 -
'tutorialspoint@2020'? Non-numeric string, skip -
2020? Integer, add to total: 2031 + 2020 = 4051
Alternative Approach Using List Comprehension
You can also solve this problem using a more concise approach ?
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
total = sum(int(element) for element in random_list
if isinstance(element, int) or (isinstance(element, str) and element.isdigit()))
print(total)
4051
Conclusion
Use isinstance() to check for integers and isdigit() to identify numeric strings. This approach safely handles mixed data types and sums only the numeric values from the list.
Advertisements
