How to delete negative elements from one list and add them to another in python?

Asked

Viewed 352 times

-5

tried with this code but does not work accurately

from random import randint

lista=10
X=list(range(lista))
R=[]

def gravarLista(X):
    for i in range(lista):
        X[i]=randint(-5, 5)
    print(X)
    for i in X:
        if i<0:
            X.pop(i)
            R.append(i)
    print(X)
    print(R)

gravarLista(X)

2 answers

3

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.

  • 1

    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.

  • 1

    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.

-1

Your program presents 3 main problems:

  1. Notice that you are filling in the list X more than once. This is redundant.
  2. You are iterating over a list and changing it at the same time, and that is dangerous. Be careful when using this gimmick.
  3. Finally, you use the function pop() and passes as argument a list value, but the function pop receives as a parameter a value of index. That is, in doing lista.pop(5) you’re not erasing the value 5, you are deleting the item located at index 5. To solve this problem, I used the function lista.index(5). This function will find the value 5, which was passed as argument, within the list lista and return your index. So:
from random import randint

lista = 10
X = []
R = []

def gravarLista(X):
    for i in range(lista):
        X.append(randint(-5, 5))
    print(X)

    for i in X:
        if i < 0:
            R.append(i)
    print(R)

    for j in R:
        if j in X:
            X.pop(X.index(j))
    print(X)


gravarLista(X)

  • 1

    As you said, iterating through a list and changing it at the same time does not work: https://ideone.com/qMLM1L

  • I corrected the reply, grateful for the remark. Follow the code working

Browser other questions tagged

You are not signed in. Login or sign up in order to post.