Print all Negative Numbers in a Range – Python
We are given a range we need to print all negative number within specific range. For example, we are given start and end point start, end = -5, 0 we need to print all numbers so that output should be -5 -4 -3 -2 -1.
Using a loop
We can use a loop to iterate through a given range and check if each number is negative. If number is negative it gets printed inside loop.
start, end = -5, 0
for i in range(start, end + 1):
if i < 0: # Check if the number is negative
print(i)
Output
-5 -4 -3 -2 -1
Explanation:
- Loop iterates through the range from -5 to 0 (inclusive) checking each number to see if it is negative.
- If number is negative (i < 0), it gets printed.
Using list comprehension
We can use list comprehension to generate a list of negative numbers within the specified range by iterating through range and filtering values less than 0.
start, end = -10, 0
# List comprehension to generate a list of negative numbers within the range
n = [i for i in range(start, end + 1) if i < 0]
print(n)
Output
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
Explanation: List comprehension iterates through the range from -10 to 0 and includes only numbers less than 0.
Using filter()
We can use filter() to apply a condition (i < 0) to range of numbers returning only negative numbers.
start, end = -10, 0 e
# Use filter() to keep only negative numbers from range and convert result to a list
n = list(filter(lambda x: x < 0, range(start, end + 1)))
print(n)
Output
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
Explanation: filter() function applies a lambda function (lambda x: x < 0) to each element in the range from -10 to 0, keeping only negative numbers.
Using map()
We can use map() to iterate over the range and apply a lambda function that checks if each number is negative then filter out non-negative values.
start, end = -10, 0
n = list(map(lambda x: x if x < 0 else None, range(start, end + 1)))
# Use list comprehension to remove None values (non-negative numbers)
n = [num for num in n if num is not None]
print(n)
Output
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
Explanation:
- The map() function applies a lambda that returns the number if it’s negative, otherwise it returns None, resulting in a list where non-negative numbers are replaced by None.
- A list comprehension filters out the None values, leaving only the negative numbers.