Python Code Example: Odd Numbers in a List

In this Python tutorial, we will learn how to identify and extract the odd numbers from a list. An odd number is a number that, when divided by 2, leaves a remainder of 1. We will create a Python program that iterates over a list of numbers, checks if each number is odd, and stores the odd numbers in a new list. This is a basic example of list iteration and conditional checking in Python.

Code Example

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

# List to store odd numbers
odd_numbers = []

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

# Output the list of odd numbers
print("Odd numbers in the list:", odd_numbers)

Output

Odd numbers in the list: [15, 33, 55, 71]

Code Explanation

  1. List of Numbers: We begin with a list of numbers: [10, 15, 22, 33, 42, 55, 60, 71, 80].
  2. Odd Number List: We initialize an empty list odd_numbers to store the odd numbers we identify.
  3. For Loop: We use a for loop to iterate over each number in the numbers list.
  4. Condition Check: Inside the loop, we use the modulo operator (%) to check if the number leaves a remainder of 1 when divided by 2 (num % 2 != 0). This indicates that the number is odd.
  5. Appending Odd Numbers: If the number is odd, we append it to the odd_numbers list using the append() method.
  6. Output: After the loop finishes, we print the list of odd numbers.

This code shows how to filter out odd numbers from a list and store them in a new list using a for loop and conditional logic.