As explained here, here and here, remove elements from a list in the same loop that iterates over it can cause problems and does not work in all cases (test the code of the another answer - to first version - with a list as [-1, -2, -3, -4, -5, 1, 2, 3]
and see that she doesn’t remove all the negatives).
To documentation gives some alternatives to solve this. One of them is to simply create another list with what you need. In this case, we can create 2 lists, one with only the positive ones and the other with only the negative ones:
def separar_negativos(numeros):
negativos = []
positivos = []
for i in numeros:
if i < 0:
negativos.append(i)
else:
positivos.append(i)
# retorna as 2 listas
return positivos, negativos
from random import choices
tamanho = 10
numeros = choices(range(-5, 6), k=tamanho)
print(numeros)
positivos, negativos = separar_negativos(numeros)
print(positivos)
print(negativos)
Note also that I used random.choices
to generate the list of random numbers, and used range(-5, 6)
(numbers between -5 and 5, since the final value is not included - I did so to be compatible with randint(-5, 5)
, which includes the 5
among the possible values) - choices
is available from Python 3.6.
Another detail is that I pass the list of numbers as the argument of the function, so it gets more "generic" - the way you did it, it’s created within the function and only works for that internally created list. Doing it the way above, no matter how the list is created, the function separates the negative and positive numbers independently of this.
gostei
of the general resolution. Therefore, this shows the true function of the code - to be useful for various situations inherent in the respective logic.– Solkarped
If the question solved your problem, mark it as the best answer. We are happy to know that we help, but do not use comments for thanks or superfluous. It may sound rude, but it helps keep the community clean. I recommend that one reading so that you can be more independent when finding errors, and that one to better understand the community and try to avoid negativities.
– yoyo