Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a List Contains Negative Numbers

Python Check Whether a List Contains Negative Numbers

Document Object Reference Manual Python3 Examples

We can check whether a list contains negative numbers by iterating over each element. If any negative number is found, we can immediately return True; otherwise, returns False。

Example

def

contains_negative

(

numbers

)

:

   

for

num

in

numbers:

       

if

num

<

0

:

           

return

True

   

return

False

Test cases

numbers

=

[

1

,

2

,

3

,

4

,

5

]

result

=

contains_negative

(

numbers

)

print

(

result

)

Code analysis:

  1. contains_negative The function takes a list numbers as its argument.
  2. Use for Loop through each element in the list num。
  3. In the loop, use if statement to check whether the current element num whether it is less than 0 (i.e., whether it is negative).
  4. If a negative number is found, return immediately True。
  5. If no negative number is found after the loop ends, return False。
  6. In the test case, the list numbers contains a negative number -4, so the function returns True。

Output result:

True

Document Object Reference Manual Python3 Examples