Python Program to Square Each Odd Number in a List using List Comprehension

List comprehension is a powerful feature in Python that allows for concise and expressive code when working with lists. It provides a compact way to perform operations on elements and create new lists based on certain conditions. In this tutorial, we'll explore how to square each odd number in a list while keeping even numbers unchanged.

Understanding the Problem

We need to write a Python program that takes a list of numbers and squares only the odd numbers. For example, given the list [1, 2, 3, 4, 5], the program should return [1, 2, 9, 4, 25], where odd numbers (1, 3, 5) are squared while even numbers (2, 4) remain unchanged.

Basic Implementation

Here's a simple approach that creates a new list with squared odd numbers and unchanged even numbers ?

def square_odd_numbers(numbers):
    result = [num ** 2 if num % 2 != 0 else num for num in numbers]
    return result

# Test the function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = square_odd_numbers(numbers)
print("Original list:", numbers)
print("Modified list:", result)
Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Modified list: [1, 2, 9, 4, 25, 6, 49, 8, 81, 10]

Alternative Approach: Only Squared Odd Numbers

If you only want the squared odd numbers (excluding even numbers entirely), use this approach ?

def get_squared_odds_only(numbers):
    squared_odds = [num ** 2 for num in numbers if num % 2 != 0]
    return squared_odds

# Test with sample data
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = get_squared_odds_only(numbers)
print("Original list:", numbers)
print("Squared odd numbers only:", result)
Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Squared odd numbers only: [1, 9, 25, 49, 81]

How List Comprehension Works

The list comprehension syntax breaks down as follows ?

# General syntax: [expression for item in iterable if condition]

numbers = [1, 2, 3, 4, 5]

# Method 1: Square odd, keep even
result1 = [num ** 2 if num % 2 != 0 else num for num in numbers]
print("Square odd, keep even:", result1)

# Method 2: Only squared odd numbers
result2 = [num ** 2 for num in numbers if num % 2 != 0]
print("Only squared odds:", result2)

# Traditional loop equivalent for comparison
result3 = []
for num in numbers:
    if num % 2 != 0:
        result3.append(num ** 2)
    else:
        result3.append(num)
print("Traditional loop result:", result3)
Square odd, keep even: [1, 2, 9, 4, 25]
Only squared odds: [1, 9, 25]
Traditional loop result: [1, 2, 9, 4, 25]

Handling Edge Cases

Let's create a more robust function that handles various edge cases ?

def square_odd_numbers_safe(numbers):
    """Square odd numbers in a list, handling edge cases."""
    if not numbers:
        return []
    
    try:
        result = [num ** 2 if num % 2 != 0 else num for num in numbers]
        return result
    except TypeError:
        print("Error: List contains non-numeric values")
        return None

# Test with different inputs
test_cases = [
    [1, 2, 3, 4, 5],
    [],
    [0, -1, -2, -3],
    [1.5, 2.5, 3.5]
]

for i, test_case in enumerate(test_cases, 1):
    result = square_odd_numbers_safe(test_case)
    print(f"Test {i}: {test_case} ? {result}")
Test 1: [1, 2, 3, 4, 5] ? [1, 2, 9, 4, 25]
Test 2: [] ? []
Test 3: [0, -1, -2, -3] ? [0, 1, -2, 9]
Test 4: [1.5, 2.5, 3.5] ? [2.25, 6.25, 12.25]

Comparison of Approaches

Approach Output Use Case
Square odd, keep even [1, 2, 9, 4, 25] Transform list preserving structure
Only squared odds [1, 9, 25] Filter and transform simultaneously
Traditional loop [1, 2, 9, 4, 25] More readable for complex logic

Conclusion

List comprehension provides an elegant solution for squaring odd numbers in a list. Use conditional expressions within list comprehension to transform elements based on conditions, or combine filtering and transformation for more specific results.

Updated on: 2026-03-27T11:55:56+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements