0

How can I print the negative numbers from this list using for loop in python?

# I have a list of numbers I want to print only the negative numbers. I'm using for loop, and my code is below. What is missing in that code? numbers = [1, 3, -4, 5, -6] for i in numbers: if i < 0: print(numbers)

26th Aug 2021, 9:09 AM
DN Josh
DN Josh - avatar
10 Respuestas
+ 6
print(i)
26th Aug 2021, 9:13 AM
Simba
Simba - avatar
+ 6
You want this? numbers = [1, 3, -4, 5, -6] print([i for i in numbers if i < 0])
26th Aug 2021, 9:21 AM
Simba
Simba - avatar
+ 3
numbers = [1, 3, -4, 5, -6] for i in numbers: if i < 0: print(i)
26th Aug 2021, 10:45 AM
Obloev Komronbek
Obloev Komronbek - avatar
+ 3
DN Josh, what does "did not work" mean. if you expect to get a useful help, you have to be a bit more specific. using print(...) in a loop means that the resulting numbers are printing in different lines. if we want to get then all in one line, we could use a comprehension as mentioned by Simba . but this also prints the squared brackets. to avoid this you can use the unpack operator: numbers = [1, 3, -4, 5, -6] print(*[i for i in numbers if i < 0]) but whatever we guess can be wrong, as long as DN Josh has not shared the required result as a sample with us.
26th Aug 2021, 11:05 AM
Lothar
Lothar - avatar
+ 2
And finally, I've solved it. Here is the full code: numbers = [1, 3, -4, 5, -6] for i in numbers: if i < 0: print (i) Thank you everyone for your contributions. Simba ,Sumit Programmer😎😎, Obloev Komronbek I'm glad to have your individual contributions. My output is -4 -6
26th Aug 2021, 4:29 PM
DN Josh
DN Josh - avatar
+ 1
Obloev Komronbek i understand your points. The expected output is: -4 -6 I've tried using print (i) but couldn't get what I'm looking for. Hence the statement "did not work". I'm a newbie in python, pardon 🙏🙏 me for my use of words.
26th Aug 2021, 12:35 PM
DN Josh
DN Josh - avatar
0
Simba not working
26th Aug 2021, 9:15 AM
DN Josh
DN Josh - avatar
0
Simba it did not work too
26th Aug 2021, 9:42 AM
DN Josh
DN Josh - avatar
0
DN Josh , thanks for your response! in this case the code from Obloev Komronbek will work fine, and also what Simba mentioned (in his first answer) should work when you replace the line in your code with his code.
26th Aug 2021, 1:48 PM
Lothar
Lothar - avatar
0
I won't forgive this very program for given me tough time since morning. I have to retaliate by writing more similar programs. Check out this and guess the output numbers = [1,4,-6,7,5, -18, -9, 8, 17, -13, 47,-91] for i in numbers: if i < 0: print(i)
26th Aug 2021, 5:59 PM
DN Josh
DN Josh - avatar