Sum of list (with string types) in Python


In this tutorial, we are going to write a program that adds all numbers from the list. List may contain numbers in string or integer format. See the example.

Input

random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]

Output

4051

Follow the below steps to write the program.

  • Initialize the list.
  • 3Initialize a variable total with 0.
  • Iterate over the list.
  • If the element is int, then add it to the total by checking two conditions.
    • The element will be int -> Check type.
    • The element will be a number in string format -> Check using isdigit() method.
  • Print the total

Example

 Live Demo

# initialzing 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 its a number or not
   if isinstance(element, int) or element.isdigit():
      # adding the element to the total
      total += int(element)
# printing the total
print(total)

Output

If you run the above code, then you will get the following result.

4051

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 11-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements