Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Print All Odd Numbers in a List

Python Print All Odd Numbers in a List

Document Object Reference Manual Python3 Examples

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

]

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 a list comprehension to iterate over numbers list, filter out all numbers not divisible by 2 (that is, odd numbers), and store them in odd_numbers list.
  3. print(odd_numbers): Print the odd_numbers all the odd numbers in the list.

Output result:

[1, 3, 5, 7, 9]

Document Object Reference Manual Python3 Examples