-4

I'm trying to make def get_neg(): so that get_neg(lst) returns "-1, -2, -3" when lst = [-1, -2, -3, 4, 5, 6]. I tried this code below, but I don't know how to get the result in 1 line.

def get_neg():
    for n in lst:
        if n < 0:
            print(str(n) + ',')
        else:
            pass

This way I get each numbers in a different row and a comma at the end. It has to be programmed with basic commands

BAbabo
  • 11
  • 2
  • 6
    Don't make your functions print, because that makes their usability very limited. Make a function that returns the result you want and then do with the result whatever you want (in your case, `print`) – matszwecja Mar 31 '22 at 11:34
  • It seems like your question is really how to print on one line: https://stackoverflow.com/questions/3249524/print-in-one-line-dynamically – Mattwmaster58 Mar 31 '22 at 11:35
  • "It has to be programmed with basic commands" — return statement is basic enough? – vikingosegundo Mar 31 '22 at 11:35
  • See also: https://stackoverflow.com/questions/26160393/using-functions-print-vs-return – Karl Knechtel Mar 31 '22 at 11:36

1 Answers1

2

You can use list comprehensions (Do not forget to give lst as an argument to the get_neg function):

def get_neg(lst):
    return [x for x in lst if x < 0]

Example

get_neg([-1,-2,4,5]) # [-1, -2]
get_neg([-15,-22,-4, 5, 0]) # [-15, -22, -4]
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29