Python Print All Odd Numbers in a List
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)
odd_numbers = [num for num in numbers if num % 2 != 0]
print(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 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.print(odd_numbers): Print outodd_numbersall the odd numbers in the list.
Output Result:
[1, 3, 5, 7, 9]Other Extensions
Python3 Examples