Delete item from a list in python

1

I do not know what I'm wrong about, I have the concept but it confuses me a bit

def eliminarEnLista(L):
   n=int(raw_input("Ingrese el numero que desea eliminar de la lista: "))       
   L=[]    
   i=0    
   while i <len(L): 
      for cont in L[i]:
          if cont <=L[i]:
              continue
          if cont==n and cont==L[i]:
              L.remove(i)
          else:
             pass
      i+=1

   return L 

I do not print anything on the screen after calling this function and I would like to know what my problem is u_u

    
asked by Wolf 21.10.2018 в 02:15
source

2 answers

2

There are several things wrong with your function.

  • You pass a list, L, by parameter, but you assign it to an empty list, so you lose the list.
  • Leaving aside two nested loops, which for this problem is not necessary, in the for loop you try to traverse L [i]. Assuming that the list L is of numbers (I assume it by raw_input), L [i] will be a number, so you can not iterate over it, and in this statement the program would fail.
  • If you do not want to do anything if the if is breached, you do not have to do an else. Putting else to pass is completely unnecessary.
  • remove does not delete by index, if not by the item in the list, so you do not have to go through the list at any time.
  • An example of how you could do it is the following. Keep in mind that the list you pass by parameter will be modified.

    def eliminarEnLista(L):
        n=int(raw_input("Ingrese el numero que desea eliminar de la lista: "))
        try:
            L.remove(n)
            print(L)
        except ValueError:
            print('{} no se encuentra en la lista'.format(n))
    L = [1,2,3]
    eliminarEnLista(L) 
    
        
    answered by 21.10.2018 / 03:04
    source
    0
    def eliminarEnLista(una_lista):
        posicion = input("¿Qué posición que desea eliminar de la lista: " + ",".join(una_lista) + " ? ")
        if(str(posicion).isdigit() and int(posicion) <= len(una_lista)):
            una_lista.pop(int(posicion))
            return ",".join(una_lista)
        else:
            return "Algo anda mal"
    
    print(eliminarEnLista(["a", "b", "c", "d", "e"]))
    
        
    answered by 21.10.2018 в 05:32