Home > Software engineering >  How can I print first negative number after a positive number in a list?
How can I print first negative number after a positive number in a list?

Time:05-30

I want to print first negative number after a positive number in a python list. But I am unable to do this

lst = [2,4,-4,-5,-7,2,3,5,6,-9,-4,-6,3,45,6,-67,-45,-56]

In this list I want to print only -4,-9,-67

CodePudding user response:

Try:

lst = [2, 4, -4, -5, -7, 2, 3, 5, 6, -9, -4, -6, 3, 45, 6, -67, -45, -56]

out = [b for a, b in zip(lst, lst[1:]) if a > 0 and b < 0]
print(out)

Prints:

[-4, -9, -67]

CodePudding user response:

you could do something like this:

for c, item in enumerate(lst): # go through all of the items and their indexs
    if item < 0 and c > 0 and lst[c - 1] >= 0: # check if the previous item is positive and the current number is negative
        print(item) # print the current item

CodePudding user response:

A little bit modified answer of @Andrej Kesely, without producing sliced list (by means of using indexes instead) you can achieve same result

out = [lst[i   1] for i in range(len(lst) - 1) if lst[i] > 0 and lst[i   1] < 0]

# [-4, -9, -67]

CodePudding user response:

With Python 3.10 :

from itertools import pairwise

for a, b in pairwise(lst):
    if a > 0 > b:
        print(b)

Without:

a = 0
for b in lst:
    if a > 0 > b:
        print(b)
    a = b

CodePudding user response:

NOTE: You haven't specified what should be the right approach to a 0 in the list, that could slightly change the answer.

The cleanest way is probably:

[b for a,b in zip(lst, lst[1:]) if a > 0 > b]

(But it's not very efficient for large lists, because it copies the list)

A more efficient way is probably:

[lst[i] for i in range(1, len(lst)) if lst[i - 1] > 0 > lst[i]]

(But it's less elegant)

You could always use iterators (...) instead of list comprehensions [...] if you need more memory efficiency as well.

  • Related