When it is required to find the sum of all even and odd digits of an integer list, a simple iteration and the ‘modulus’ operator are used.
Below is a demonstration of the same −
Example
my_list = [369, 793, 2848, 4314, 57467] print("The list is :") print(my_list) sum_odd = 0 sum_even = 0 for index in my_list: for element in str(index): if int(element) % 2 == 0: sum_even += int(element) else: sum_odd += int(element) print("The result is :") print("The sum of odd digits is :") print(sum_odd) print("The sum of odd digits is :") print(sum_even)
Output
The list is : [369, 793, 2848, 4314, 57467] The result is : The sum of odd digits is : 54 The sum of odd digits is : 46
Explanation
A list of integers is defined and is displayed on the console.
Two variables ‘sum_odd’ and ‘sum_even’ are declared.
The list is iterated over, and the sum of odd digits and even digits are calculated.
This is done by getting the modulus of the element with 2, and comparing it with 0.
This is the output that is displayed on the console.