Python program to print positive numbers in a list
In this article, we will learn to create a python program to print positive numbers in a list.
Print positive numbers in a list using 2 different methods:
- Using loop
- Using list comprehension
Loop
Explanation
- Initialize the list.
- Then, iterate all numbers from the list and check if the number is greater or equal to 0 or not.
- If the number is greater or equal to 0, then append those numbers to a new list named result.
- Then, lastly, print results.
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # list contains all numbers list = [1, 5, 22, -5, 55, -21] # result result = [] # iterate all numbers for num in list: # check for a positive number if num >= 0: result.append(num) #append all number to result # print result print(result) |
Output
[1, 5, 22, 55]
List comprehension
Explanation
- Initialize the list.
- Then using list comprehension, store all the positive numbers in a result.
- Then print the result.
Program
1 2 3 4 5 6 7 8 | # list contains all numbers list = [1, 5, 22, -5, 55, -21] # list comprehension result = [num for num in list if num>=0] # print rsult print(result) |
Output
[1, 5, 22, 55]