Print all positive numbers from a list in Python

In this tutorial, We are going to learn, how to print all positive numbers from a list in Python.
There are various ways to find all positive numbers from a list in Python. As we know that elements of the list are stored in [ ] braces separated by a comma (,). To find positive numbers from the list, We will generate a random list. Using the same list we will try to find all positive numbers from the same list.

How to print only positive numbers from a list in Python

Let us generate a random list:

a=[2,-4,6,-10,22,34]

We have generated a list in variable a. Let us find out all positive numbers store in list elements in multiple ways.

  • Using the “for” loop: As we know that all numbers greater than zero are positive numbers. So using for loop and applying the same
    condition, We can easily identify positive numbers from a list.
a=[2,-4,6,-10,22,34]
for i in a:
    if i>=0:
        print(i,' ' ,end='')

As we can see from the list. We have (2,6,22,34) as a positive number. So it should return (2,6,22,34).

2  6  22  34
  • Using list comprehension: List comprehension is somehow like for loop. Using list comprehension, We will get all the positive numbers in the form of the list stored in another variable.
a=[2,-4,6,-10,22,34] 
b = [i for i in a if i>= 0] 
print(b)
[2, 6, 22, 34]
  • Using a “while” loop: Using a while loop and applying to slice on each element of a list we can easily check whether the number is positive or not.
a=[2,-4,6,-10,22,34]
num=0
while(num < len(a)): 
    if a[num] >= 0: 
        print(a[num], end = " ")  
    num += 1
2 6 22 34
  • Using the “lambda” function: As we know, the lambda function applies the condition in each element. So, Using lambda we can check whether the number is greater than zero or not. If it is greater than zero, It will print the list of all positive numbers.
a=[2,-4,6,-10,22,34]
b=list(filter(lambda x:(x >= 0),a)) 
print(b)
[2, 6, 22, 34]

 

Leave a Reply

Your email address will not be published. Required fields are marked *