Python program to print negative numbers in a list
In this article, we will explore multiple approaches to find and print negative numbers in a list.
Example:
Input: lst = [12, -7, 5, 64, -14]
Output: -7, -14
Using List Comprehension
List comprehension provides a compact way to filter negative numbers while keeping the code readable.
a = [5, -3, 7, -1, 2, -9, 4]
n = [num for num in a if num < 0]
print(n)
Output
[-10, -5, -2]
Explanation:
- Iterates through each element in a.
- Adds the number to the new list negatives only if it is less than 0.
Using filter() Function
The filter() function allows filtering elements based on a condition efficiently.
a = [5, -3, 7, -1, 2, -9, 4]
n = list(filter(lambda x: x < 0, a))
print(n)
Output
[-3, -1, -9]
Explanation:
- lambda x: x < 0 defines lambda function returning True for negative numbers.
- filter(lambda x: x < 0, a): filters elements in list a that satisfy the condition x < 0.
- list(...): Converts the filtered result into a list.
Using a For Loop
A traditional for loop can be used to iterate through the list and print negative numbers directly.
a = [5, -3, 7, -1, 2, -9, 4]
for num in a:
if num < 0:
print(num)
Output
-3 -1 -9
Explanation:
- "for loop" iterates through each element.
- "if num < 0" checks the condition if num is negative.
- Print the number if it is negative.
Using map() Function
Using map() is less straightforward since it requires handling None values for non-negative numbers.
a = [5, -3, 7, -1, 2, -9, 4]
negatives = [num for num in map(lambda x: x if x < 0 else None, a) if num is not None]
print(negatives)
Output
[-3, -1, -9]
Explanation:
- map() applies a lambda function to each element.
- Non-negative numbers are converted to None.
- A list comprehension filters out None values.