Sum Even and Odd Values with One For-Loop and No If-Condition Using Python
Last Updated :
08 Sep, 2024
Summing even and odd numbers in a list is a common programming task. Typically, we'd use an if condition to check whether a number is even or odd. However, we can achieve this in Python efficiently using arithmetic operators and list slicing, without relying on if conditions. In this article, we'll explore how to sum even and odd values in Python using a single loop and arithmetic operations.
1. Use of Arithmetic Operators to Detect Even and Odd Numbers
In Python, we can easily determine if a number is even or odd using the modulo operator (%).
For example:
- number % 2 == 0 returns True if the number is even.
- number % 2 != 0 or number % 2 == 1 returns True if the number is odd.
However, our task is to sum even and odd numbers without explicitly using if conditions inside the loop. Instead, we can leverage arithmetic operators such as modulo and clever mathematical manipulation to handle both sums simultaneously.
Key Idea:
- num % 2 == 0: Evaluates to True (1) if the number is even, otherwise False (0).
- num % 2 == 1: Evaluates to True (1) if the number is odd, otherwise False (0).
By multiplying the number with the boolean value, we effectively add it to the sum only if it meets the condition (even or odd).
Python
def sum_even_odd(numbers):
even_sum = 0
odd_sum = 0
for num in numbers:
even_sum += num * (num % 2 == 0)
odd_sum += num * (num % 2 == 1)
return even_sum, odd_sum
numbers = [1, 2, 3, 4, 5, 6, 7, 9, 11, 12, 14]
even, odd = sum_even_odd(numbers)
print("Sum of even numbers:", even)
print("Sum of odd numbers:", odd)
OutputSum of even numbers: 38
Sum of odd numbers: 36
Another Approach
Python
def sum_even_odd(numbers):
even_sum = 0
odd_sum = 0
for n in numbers:
even_sum += (1 - n % 2) * n
odd_sum += (n % 2) * n
return even_sum, odd_sum
numbers = [1, 2, 3, 4, 5, 6, 8, 7, 12, 9]
even, odd = sum_even_odd(numbers)
print("Sum of even numbers:", even)
print("Sum of odd numbers:", odd)
OutputSum of even numbers: 32
Sum of odd numbers: 25
Explanation:
- (i-n%2): Evaluates to (1) if the number is even, otherwise (0).
- (n % 2): Evaluates to (1) if the number is odd, otherwise (0).
Python allows us to extract elements from lists at specific intervals using step-slicing. This means we can create two separate lists:
- One for the even-indexed numbers.
- One for the odd-indexed numbers.
Given a list of numbers, slicing with a step of 2 will allow us to isolate the even and odd indexed values. Here's how it works:
- numbers[::2] gives us all elements at even indices (0, 2, 4, …).
- numbers[1::2] gives us all elements at odd indices (1, 3, 5, …).
Although this slicing pattern refers to indices, we can combine it with mathematical operations to sum only even or odd values, without relying on if conditions.
Example:
Consider a list of integers, numbers. By slicing the list as described, we can sum the even and odd values in a single loop.
Approach:
- Iterate over the list.
- Use list slicing to handle the even and odd values separately.
- Sum both even and odd numbers in one go without using if conditions.
Here's an example implementation to sum even and odd numbers with one loop and no if condition using slicing:
Python
# Sample list of integers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Step 1: Separate the even and odd numbers based on indices using slicing
even_numbers = numbers[1::2] # Odd index values (but these are even numbers)
odd_numbers = numbers[::2] # Even index values (but these are odd numbers)
# Step 2: Calculate the sum of even and odd numbers
sum_even = sum(even_numbers)
sum_odd = sum(odd_numbers)
# Step 3: Output the results
print(f"Sum of even numbers: {sum_even}")
print(f"Sum of odd numbers: {sum_odd}")
OutputSum of even numbers: 30
Sum of odd numbers: 25
Explanation:
- Step 1: We use slicing to create two separate lists: one for numbers at odd indices (even_numbers), which are technically even numbers, and another for numbers at even indices (odd_numbers), which are odd numbers.
- Step 2: We use Python's built-in sum() function to calculate the sum of each list.
- Step 3: Finally, we print the results.
Conclusion
Summing even and odd numbers in Python doesn't necessarily require if conditions. By leveraging arithmetic properties and Python's powerful list slicing capabilities, we can separate and sum even and odd values with ease. This method not only simplifies the code but also reduces conditional checks inside the loop, making the process more efficient.
With Python’s slicing and mathematical tricks, we can handle a variety of scenarios that require summing specific types of values without conditional logic, providing a cleaner and more efficient approach
Similar Reads
Using Else Conditional Statement With For loop in Python Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while
2 min read
Counting the number of even and odd elements in a vector using a for loop? In this article, we will discuss how to find the number of even and odd elements in a vector with its working example in the R Programming Language using R for loop. Syntax:vector <- c(...) # Replace ... with the vector elementseven_count <- 0odd_count <- 0for (element in vector) { if (elem
2 min read
Difference between Sums of Odd and Even Digits in Python Write a python program for a given long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for the leftmost digit). Examples: Input: 1212112Output: YesExplanation:the odd position element is 2+2+1=5the even
2 min read
Python Program for Number of elements with odd factors in given range Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output :
2 min read
Count of odd sum Submatrix with odd element count in the Matrix Given a matrix mat[][] of size N x N, the task is to count the number of submatrices with the following properties: The sum of all elements in the submatrix is odd.The number of elements in the submatrix is odd.Examples: Input: mat[][] = {{1, 2, 3}, {7, 5, 9}, {6, 8, 10}}Output: 8Explanation: As her
15 min read