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?
JavaScript
x
46
46
1
def crud(name, lista):
2
print('----------------------------')
3
print(name.capitalize())
4
print('----------------------------')
5
print('t[1] . Ingresar')
6
print('t[2] . Consultar')
7
print('t[3] . Eliminar')
8
print('t[4] . Actualizar')
9
print('t[5] . Listar')
10
opcion = int(input('OPCIÓN >>> '))
11
12
if opcion == 1:
13
lista.append(input('Ingrese nombre del '+str(name[:-2])+': '))
14
if opcion == 2:
15
node_id = int(input('Ingrese id del '+str(name[:-2])+' a consultar: '))
16
elif opcion == 5:
17
i = 0
18
while i <= len(lista)-1:
19
print('t['+str(i)+'] . '+str(lista[i]))
20
i += 1
21
22
while True:
23
print('----------------------------')
24
print('ALMACÉN MARKET-CICLE')
25
print('PROGRAMA PRINCIPAL')
26
print('----------------------------')
27
print('t[1] . Vendedores')
28
print('t[2] . Productos')
29
print('t[3] . Clientes')
30
print('t[4] . Ventas')
31
print('t[5] . SALIR')
32
opcion = int(input('OPCIÓN >>> '))
33
34
lista_vendedores = []
35
lista_productos = []
36
lista_clientes = []
37
38
if opcion == 1:
39
crud('vendedores', lista_vendedores)
40
if opcion == 2:
41
crud('productos', lista_productos)
42
if opcion == 3:
43
crud('clientes', lista_clientes)
44
elif opcion == 5:
45
break
46
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:
JavaScript
1
8
1
def func(items):
2
items.append(1)
3
print(items)
4
5
while True:
6
foobar = []
7
func(foobar)
8
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.