Python Program to Print Positive Numbers in a List
Given a list of numbers, the task is to print all positive numbers in the list. A positive number is any number greater than 0.
For example:
a = [-10, 15, 0, 20, -5, 30, -2]
Positive numbers = 15, 20, 30
Using NumPy
This method uses NumPy arrays to efficiently extract all positive numbers at once using boolean indexing.
import numpy as np
a = np.array([-10, 15, 0, 20, -5, 30, -2])
res = a[a > 0]
print(res)
Output
[15 20 30]
Using List Comprehension
This method creates a new list of positive numbers using list comprehension in one line by checking each element of the original list.
a = [-10, 15, 0, 20, -5, 30, -2]
res = [i for i in a if i > 0]
print(res)
Output
[15, 20, 30]
Using filter() Function
The filter() function can select elements from the list that meet a given condition. We use it with a lambda function to filter positive numbers.
a = [-10, 15, 0, 20, -5, 30, -2]
res = filter(lambda x: x > 0, a)
print(list(res))
Output
[15, 20, 30]
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]
for val in a:
if val > 0:
print(val)
Output
15 20 30