Python Print All Odd Numbers in a List

Document 对象参考手册Python3 Examples

In Python, we can filter out all the odd numbers by iterating through the list and using conditional judgment. Odd numbers are integers that cannot be divided evenly by 2.

Example

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = [num for num in numbers if num % 2 != 0]
print(odd_numbers)

Code Analysis:

  1. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: Define a list containing integers.
  2. odd_numbers = [num for num in numbers if num % 2 != 0]: Use list comprehension to iterate through thenumberslist, filter out all numbers that cannot be divided evenly by 2 (i.e., odd numbers), and store them in theodd_numberslist.
  3. print(odd_numbers): Print outodd_numbersall the odd numbers in the list.

Output Result:

[1, 3, 5, 7, 9]

Document 对象参考手册Python3 Examples

Other Extensions