CodexBloom - Programming Q&A Platform

Python - advanced patterns When Appending to a List Inside a Loop with a Condition

👀 Views: 9964 💬 Answers: 1 📅 Created: 2025-06-05
python lists looping best-practices Python

I'm working with unexpected behavior when trying to append values to a list inside a loop that has a conditional check. I'm using Python 3.9 and wanted to maintain a list of even numbers from a given range. The following code snippet demonstrates the scenario: ```python numbers = [] for i in range(10): if i % 2 == 0: numbers.append(i) else: numbers.append(i * 2) # This is intended to append twice the value for odd numbers. ``` Upon running this code, I expected the list to contain only even numbers, but it includes doubled values of odd numbers as well. I want to create a list of only even numbers, and the odd numbers should be ignored entirely. When I try to isolate the even numbers correctly, removing the else clause leads to what I expected, but I need to keep the logic for odd numbers in some cases. How can I rewrite this loop such that I can either collect even numbers while having the option to handle odd numbers differently without affecting the resultant list? I'm looking for a clean solution that adheres to best practices in Python. I’ve tried using list comprehensions, but I want to keep this computation understandable for my team. Thanks for any help!