Python program to print negative numbers in a list

 In this article, we will learn to create a python program to print negative numbers in a list.

Print negative numbers in a list using 2 different methods:

  1. Using loop
  2. Using list comprehension


Loop

Explanation

  1. Initialize the list.
  2. Then, iterate all numbers from the list and check if the number is lesser than 0 or not.
  3. If the number is lesser than 0, then append those numbers to a new list named result.
  4. 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 negative number
    if num < 0:
       result.append(num)  #append all number to result

# print result
print(result)

Output

[-5, -21]


List comprehension 

Explanation

  1. Initialize the list.
  2. Then using list comprehension, store all the negative numbers in a result.
  3. 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

[-5, -21]
Next Post Previous Post
No Comment
Add Comment
comment url