Python Check if a List Contains Negative Numbers

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. contains_negativeThe function accepts a listnumbersas a parameter.
  2. Useforloop to iterate through each element in the listnum。
  3. In the loop, useifstatement to check whether the current elementnumis less than 0 (i.e., whether it is a negative number).
  4. If a negative number is found, return immediatelyTrue。
  5. If no negative number is found after the loop ends, returnFalse。
  6. In the test case, the listnumberscontains a negative number-4, so the function returnsTrue。

Output result:

True

Document 对象参考手册Python3 Examples

Other Extensions