Javaexercise.com

How to Find Sum of Even and Odd Values of Python List

This article includes some programming examples to find the sum of even and odd values of the Python list. This is a common problem we face when we either find even/odd values or find their sum in the list.

Algorithm

Step 1: Take a list as input

Step 2: Create two variables even_sum and odd_sum and initialize them to zero

Step 3: Iterate a loop for all the values in the list

Step 4: Check if the value is even or odd by using the modulo(%) operator.

Step 5: Calculate the sum of even or odd values

Step 6: Repeat step 3, 4, and 5 until the loop exits

Step 7: Display the result

 

Python Program To Find Sum of Even and Odd Values of list

In this example, we used the modulo operator to check whether the value is even or odd and then get sum of these values in even_sum and odd_sum variables respectively. 

# Take a list
list1 = [12,32,54,12,6,8,11]
even_sum = 0
odd_sum = 0
print(list1)
# Get sum of odd and even values
for val in list1:
  if val%2 == 0:
    even_sum += val
  else:
    odd_sum += val
# Display result
print("Sum of even values : ", even_sum)
print("Sum of odd values: ", odd_sum)


Output

[12, 32, 54, 12, 6, 8, 11]

Sum of even values:  124

Sum of odd values:  11

 

Python Program To Find Sum of Even Values of list

We can use the list comprehension technique to get sum of even values in a simple and concise way. It is useful if we want a single-line solution. See the code and output.

# Take a list
list1 = [12,32,54,12,6,8,11]
even_sum = 0
print(list1)
# Get sum of even values
even_sum = sum([num for num in list1 if num % 2 == 0])
# Display result
print("Sum of even values : ", even_sum)


Output:

[12, 32, 54, 12, 6, 8, 11]

Sum of even values :  124