Python Code Example: Even Numbers in a List

In this Python tutorial, we will learn how to identify and extract the even numbers from a list. An even number is a number that is divisible by 2 without any remainder. We will create a Python program that iterates over a list of numbers, checks if they are even, and stores the even numbers in a separate list. This is a simple exercise in list iteration and conditional statements.

Code Example

# List of numbers
numbers = [10, 15, 22, 33, 42, 55, 60, 71, 80]

# List to store even numbers
even_numbers = []

# Iterating through the list
for num in numbers:
    if num % 2 == 0:  # Check if the number is even
        even_numbers.append(num)  # Add even number to the list

# Output the list of even numbers
print("Even numbers in the list:", even_numbers)

Output

Even numbers in the list: [10, 22, 42, 60, 80]

Code Explanation

  1. List of Numbers: We start with a list of numbers: [10, 15, 22, 33, 42, 55, 60, 71, 80].
  2. Even Number List: We initialize an empty list even_numbers to store the even numbers we find.
  3. For Loop: We loop through each number in the numbers list using a for loop.
  4. Condition Check: Inside the loop, we use the modulo operator (%) to check if the number is divisible by 2 (num % 2 == 0). If the condition is true, the number is even.
  5. Appending Even Numbers: If the number is even, we append it to the even_numbers list using the append() method.
  6. Output: After the loop completes, we print the list of even numbers.

This code demonstrates how to filter even numbers from a list efficiently in Python using a for loop and conditional statements.