Python Print All Odd Numbers in a List
In Python, we can iterate over a list and use a conditional check to filter out all odd numbers. An odd number is an integer that is not divisible 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
]
(
odd_numbers
)
Code analysis:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: Define a list containing integers.odd_numbers = [num for num in numbers if num % 2 != 0]: use a list comprehension to iterate overnumberslist, filter out all numbers not divisible by 2 (that is, odd numbers), and store them inodd_numberslist.print(odd_numbers): Print theodd_numbersall the odd numbers in the list.
Output result:
[1, 3, 5, 7, 9]
Python3 Examples