Calculate Sum Get User Input Patterns Program Find Area of CircleFind Area of Rectangle Perimeter of Rectangle Find Even and Odd Numbers Find Sum of Digit in Python Find Factorial in PythonPrint Fibonacci Series Check Armstrong Number Reverse a Number Check Palindrome Number Swap Two Numbers Matrix MultiplicationFind Perfect NumberAdd Two Matrix in Python Find Sum of Squares Find Sum of Cubes Find URL in String
Find Largest in List Find Duplicate in List Check Alphabet Remove Duplicate Elements from List Reverse List Elements Find Element in Python List Interchange first and last element in List Find Even Numbers in List Find Length of a List Find Sum of list Elements Find Elements in List Get the product of List elements Interchange List Elements Find Smallest Elements in List Find Max Value in a 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.
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
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
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