Python Check if a List Contains Negative Numbers
We can determine whether a list contains negative numbers by iterating through each element in the list. If any negative number is found, we can immediately returnTrue, otherwise returnFalse。
Example
def contains_negative(numbers):
for num in numbers:
if num < 0:
return True
return False
# Test case
numbers = [1, 2, 3, -4, 5]
result = contains_negative(numbers)
print(result)
for num in numbers:
if num < 0:
return True
return False
# Test case
numbers = [1, 2, 3, -4, 5]
result = contains_negative(numbers)
print(result)
Code explanation:
contains_negativeThe function accepts a listnumbersas a parameter.- Use
forloop to iterate through each element in the listnum。 - In the loop, use
ifstatement to check whether the current elementnumis less than 0 (i.e., whether it is a negative number). - If a negative number is found, return immediately
True。 - If no negative number is found after the loop ends, return
False。 - In the test case, the list
numberscontains a negative number-4, so the function returnsTrue。
Output result:
TrueOther Extensions
Python3 Examples