Python - Identify a negative number in a list

95,980

Solution 1

Break your problem down. Can you identify a way to check if a number is negative?

if number < 0:
    ...

Now, we have many numbers, so we loop over them:

for number in numbers:
    if number < 0:
        ...

So what do we want to do? Count them. So we do so:

count = 0
for number in numbers:
    if number < 0:
        count += 1

More optimally, this can be done very easily using a generator expression and the sum() built-in:

>>> numbers = [1, 2, -3, 3, -7, 5, 4, -1, 4, 5]
>>> sum(1 for number in numbers if number < 0)
3

Solution 2

sum(n < 0 for n in nums)

This is the most pythonic way to do it.

Solution 3

Or you could use filter to "filter" out the negatives.

total = len(filter(lambda x: x < 0, my_list))

Share:
95,980
Michael
Author by

Michael

Updated on April 14, 2020

Comments

  • Michael
    Michael about 4 years

    I need help doing a program which should recieve ten numbers and return me the number of negative integers i typed. Example: if i enter:

    1,2,-3,3,-7,5,4,-1,4,5
    

    the program should return me 3. I dont really have a clue, so please give me a hand :) PS. Sorry for my bad english, I hope you understand