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
# 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.