Skip to content

Python sum list of strings | Example code

  • by

Use type() and isdigit() functions in Python to achieve a sum list of strings in Python. This function will check If the element is int, then add it to the total by checking two conditions.

Example sum list of strings in Python

A simple example code adds all numbers from the list. Where the given list may contain numbers in string or integer format.

lst = [1, '10', 'Hello', '2020', 'Python@2020', 2021]

total = 0
# iterating over the list
for element in lst:
    # checking whether its a number or not
    if isinstance(element, int) or element.isdigit():
        # adding the element to the total
        total += int(element)



Python sum list of strings

Or use List comprehension

total = sum([int(i) for i in lst if type(i)== int or i.isdigit()])

How to sum a list of string objects in Python?

Answer: Print only the first letter of each word in order to make one new word.

if words are separated by space, then split in words using space and for each word (“map” function), take the first character (x[0]). Last join the result using void.

s = "this is my sentence"

res = "".join(map(lambda x: x[0], s.split(" ")))


Or simple use

res = "".join(x[0] for x in s.split())

Output: tims

Comment if you have any doubts or suggestions on this Python sum topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *