I have a function in which I get a list and I want to use this list in another function:
def funcao1():
...
lista1 = [.....]
def funcao2():
#preciso de chamar a lista aqui
I have a function in which I get a list and I want to use this list in another function:
def funcao1():
...
lista1 = [.....]
def funcao2():
#preciso de chamar a lista aqui
Returns the list in function 1 and calls function 1 inside function 2:
def funcao1():
...
lista1 = [.....]
return lista1
def funcao2():
#preciso de chamar a lista aqui
lista = funcao1()
funcao2()
Either declare the list externally and pass the parameter to the two functions:
def funcao1(lista):
lista.append('valor da funcao 1')
def funcao2(lista):
print lista
lista = ['valor1', 'valor2']
funcao1(lista)
funcao2(lista)
The best solution in my opinion, when it is necessary to use a given function from one function in another is: either use return
or use argument passing for it:
Example using argument passing:
lista = [1, 2, 3]
def funcao1 (lista):
if (type(lista) is not list) return False
#faz alguma coisa com a lsita
return
def funcao2 (lista):
// faz alguma coisa com a lsita
return
funcao1(lista);
funcao2(lista);
Example using return:
def funcao ():
lista = [1, 2, 3]
// faz alguma coisa com a lsita
return lista;
lista = funcao1()
funcao2(lista);
In addition to passing as a parameter or setting externally, you can also make the list a global variable. Example:
def primeiro():
global lista
lista = [0, 1, 2, 3]
def segundo():
return lista
In this case, once you execute the function first, it would define the list variable as a global variable. It can be used in the second function, for example. However, it is still preferable to pass the list as a parameter or even to define it externally. This way you avoid mistakes and make code maintenance easier.