How to return a negative number in python

Using the following as an example:

PosList = [1,2,3,4,5]
NegList = [-1,-2,-3,-4,-5]

If I want to get a positive value from numbers in an array I can do the following:

PosNum = [abs[i] for i in NegList]
PosNum
[Output][1, 2, 3, 4, 5]

But if I want to do a similar task to return negative numbers from a positive list of numbers I am not aware of a standard function to do this. I can do something like this:

minus = '-'
NegNum = [int[minus + str[i]] for i in PosList]
NegNum
[Output][-1, -2, -3, -4, -5]

But surely there are much better ways of doing this task that I am overlooking...

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a list of numbers, write a Python program to print all negative numbers in the given list. 

    Example:

    Input: list1 = [12, -7, 5, 64, -14]
    Output: -7, -14
    
    Input: list2 = [12, 14, -95, 3]
    Output: -95

    Example #1: Print all negative numbers from the given list using for loop Iterate each element in the list using for loop and check if the number is less than 0. If the condition satisfies, then only print the number. 

    Python3

    list1 = [11, -21, 0, 45, 66, -93]

    for num in list1:

        if num < 0:

        print[num, end=" "]

    Output:

    -21 -93 

    Example #2: Using while loop 

    Python3

    list1 = [-10, 21, -4, -45, -66, 93]

    num = 0

    while[num < len[list1]]:

        if list1[num] < 0:

            print[list1[num], end=" "]

        num += 1

    Output:

    -10 -4 -45 -66 

    Example #3: Using list comprehension 

    Python3

    list1 = [-10, -21, -4, 45, -66, 93]

    neg_nos = [num for num in list1 if num < 0]

    print["Negative numbers in the list: ", *neg_nos]

    Output

    Negative numbers in the list:  -10 -21 -4 -66
    

    Example #4: Using lambda expressions 

    Python3

    list1 = [-10, 21, 4, -45, -66, 93, -11]

    neg_nos = list[filter[lambda x: [x < 0], list1]]

    print["Negative numbers in the list: ", *neg_nos]

    Output

    Negative numbers in the list:  -10 -45 -66 -11
    

    Method: Using enumerate function 

    Python3

    l=[12, -7, 5, 64, -14]

    print[[a for j,a in enumerate[l] if a

    Chủ Đề