Python program to print positive numbers in a list
Last Updated :
29 Nov, 2024
Improve
In this article, we will explore various methods to o print positive numbers in a list. The simplest way to do is by using for loop function.
Using Loop
The most basic method for printing positive numbers is to use a for loop to iterate through the list and check each element.
a = [-10, 15, 0, 20, -5, 30, -2]
# Using a for loop to print positive number
for val in a:
if val > 0:
print(val)
Output
15 20 30
Explanation:
- Iterates over the list numbers.
- For each number checks if the number is greater than 0 (val > 0).
- If the condition is true than print the number.
Using List Comprehension
List comprehension provides a compact and Pythonic way to filter positive numbers.
a = [-10, 15, 0, 20, -5, 30, -2]
# List comprehension to filter positive numbers
res = [i for i in a if i > 0]
print(res)
Output
[15, 20, 30]
Using filter() Function
The filter() function can be used to filter out positive numbers from the list.
a = [-10, 15, 0, 20, -5, 30, -2]
# Using filter() to get positive numbers
res = filter(lambda x: x > 0, a)
# Convert filter object to list and print
print(list(res))
Output
[15, 20, 30]