Python program to print negative numbers in a list
In Python, it’s often necessary to find and print negative numbers from a list. In this article we will explore various approches to print negative numbers in a list. The most basic method for printing negative numbers is to use a for loop to iterate through the list and check each element.
a = [5, -3, 7, -1, 2, -9, 4]
# Loop through the list and print negative numbers
for num in a:
if num < 0:
print(num)
Output
-3 -1 -9
Let’s explore other method to print negative numbers in a list:
Using List Comprehension
List comprehension is a more efficient way to extract negative numbers from a list. It allows us to write the same logic in a more compact form.
a = [5, -3, 7, -1, 2, -9, 4]
# Using list comprehension to filter negative numbers
n = [num for num in a if num < 0]
print(n)
Output
[-10, -5, -2]
Using the Filter Function
filter() function is another efficient way to extract negative numbers. It allows us to filter elements from a list based on a condition.
a = [5, -3, 7, -1, 2, -9, 4]
# Using filter function to find negative numbers
n = list(filter(lambda x: x < 0, a))
print(n)
Output
[-3, -1, -9]
Explanation:
- In this method, the filter() function goes through each number in the list and applies the condition (x < 0) to check if it’s negative. The result is converted back into a list and printed.
Using the map() Function
map() function applies a function to all items in the list. We can use map() to filter negative numbers, though it requires an extra step of converting the result back into a list and checking for negative numbers.
a = [5, -3, 7, -1, 2, -9, 4]
# Using map to filter negative numbers
n = list(map(lambda x: x if x < 0 else None, a))
# Removing None values and printing negative numbers
n = [num for num in n if num is not None]
print(n)
Output
[-3, -1, -9]