How to access a list resulting from one function in another?

Asked

Viewed 2,390 times

1

I have a function in which I got a list and I intend to use that list in another function:

def funcao1():
...
lista1 = [.....]


def funcao2():
#preciso de chamar a lista aqui

3 answers

1


Returns the list in function 1 and calls function 1 within function 2:

def funcao1():
    ...
    lista1 = [.....]
    return lista1

def funcao2():
    #preciso de chamar a lista aqui
    lista = funcao1()

funcao2()

Or declares the list externally and passes by parameter for the two functions:

def funcao1(lista):
    lista.append('valor da funcao 1')

def funcao2(lista):
    print lista

lista = ['valor1', 'valor2']
funcao1(lista)
funcao2(lista)

1

In addition to passing as parameter or setting externally, you can also turn the list into a global variable. Example:

def primeiro():
   global lista
   lista = [0, 1, 2, 3]
def segundo():
   return lista

In this case, once you run the function first, it would define the list variable as a global variable. It can be used in the function according to, for example. However, it is still preferable to pass the list as parameter or even to define it externally. This way you can avoid errors and make code maintenance easier.

0

The best solution in my view when it is necessary to use a given function in another is: or use the return or use the passage of arguments to do so:

Example using the passage of arguments:

 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 the return:

def funcao ():
     lista = [1, 2, 3]
     // faz alguma coisa com a lsita
     return lista;


lista = funcao1()

funcao2(lista);
  • I didn’t realize what the " list = function1() ... function2(list)"

  • Basically, the purpose of the first function is to give that list and then in the second function I have to use that list

  • The return of a function is a result obtained by calling that function. When you do lista = funcao1(), you are assigning the value produced by funcao1 to a variable called lista. This is the most appropriate way to pass values from one function to another. When you do funcao2(lista), you are making available to funcao2 the object lista.

  • But then to use the list in the 2nd function I have to do the " function2(list)" where ?

Browser other questions tagged

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