Skip to content
Advertisement

Append an input to a method parameter list

I’m using a generic local crud so i can implement the same method for every single list, but when trying to add a value to a list it doesn’t update the root list but the parameter one does, any help?

def crud(name, lista):
    print('----------------------------')
    print(name.capitalize())
    print('----------------------------')
    print('t[1] . Ingresar')
    print('t[2] . Consultar')
    print('t[3] . Eliminar')
    print('t[4] . Actualizar')
    print('t[5] . Listar')
    opcion = int(input('OPCIÓN >>> '))

    if opcion == 1:
        lista.append(input('Ingrese nombre del '+str(name[:-2])+': '))
    if opcion == 2:
        node_id = int(input('Ingrese id del '+str(name[:-2])+' a consultar: '))
    elif opcion == 5:
        i = 0
        while i <= len(lista)-1:
            print('t['+str(i)+'] . '+str(lista[i]))
            i += 1

while True:
    print('----------------------------')
    print('ALMACÉN MARKET-CICLE')
    print('PROGRAMA PRINCIPAL')
    print('----------------------------')
    print('t[1] . Vendedores')
    print('t[2] . Productos')
    print('t[3] . Clientes')
    print('t[4] . Ventas')
    print('t[5] . SALIR')
    opcion = int(input('OPCIÓN >>> '))

    lista_vendedores = []
    lista_productos = []
    lista_clientes = []

    if opcion == 1:
        crud('vendedores', lista_vendedores)
    if opcion == 2:
        crud('productos', lista_productos)
    if opcion == 3:
        crud('clientes', lista_clientes)
    elif opcion == 5:
        break

If i print the parameter “lista” when appends the new value it returns the list with the new value, but when i enter the list option, the list shows empty.

Advertisement

Answer

You create a new empty list on every iteration of while True:

def func(items):
    items.append(1)
    print(items)
   
while True:
    foobar = []
    func(foobar)

will always give [1], not [1], [1,1], ….

Don’t run the above, it will just busy loop until it explodes.

To solve your issue, you need to declare the list once, outside your interactive loop.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement