to3
to3

Reputation: 29

How to access list/dictionary in a function from a different function

I'm new to python and I was wondering if there's a way for me to access a list or dictionary with data already stored in it from a different function.

I was wondering if there's a way for me to make the list global so I can access it outside the function, or any other alternative solution.

def upload():
    numlist = [1,2,3,4]

def add():
   for i in numlist:
       print(i)

Upvotes: 0

Views: 104

Answers (4)

Hunted
Hunted

Reputation: 88

No, you can't access local variables outside of their functions.

An option would be to define a Class that contains:

  1. The variables you're using
  2. The functions that need access to these variables.

This would allow you to define local variables that can be accessed by all of the functions in the class without having to return values from one function to the next.

Example :

class Upload:
    def __init__(self):
        self.numlist = [1,2,3,4]

    def add(self):
        for i in self.numlist:
            print(i)

foo = Upload()
foo.add()

Output :

1
2
3
4

Upvotes: 0

Tom Dalton
Tom Dalton

Reputation: 6190

Generally speaking global variables are not brilliant, so it would be better to have a function that creates and returns the list, and then use that in the second function. Even better, you could have a 3rd function that coordinates the 2 separate parts - creation of the list, and processing of the list:

def create_numlist(): 
    numlist = [1,2,3,4]
    return numlist

def print_numbers(numbers):
    for i in numbers:
        print(i)

def main():
    numbers = create_numlist()
    print_numbers(numbers)

Now the function that loads/creates the list is completely separate from the function that does something with that list.

Upvotes: 4

H_DANILO
H_DANILO

Reputation: 321

One option is to pass it as parameter, hooking everything together

def add(add_list):
  for value in add_list:
    print(value)

def upload():
  numlist = [1, 2, 3, 4]
  add(numlist)

Upvotes: 1

Anentropic
Anentropic

Reputation: 33843

Yes, as you guessed you can make the list global.

You just need to declare it outside of the function (otherwise it is only local to the function).

numlist = None

def upload():
    global numlist
    numlist = [1,2,3,4]

def add():
    for i in numlist:
        print(i)

upload()
add()

Global variables are somewhat frowned upon. You might research this topic in some depth, for example Why are global variables evil?

Therefore it would be better to try and structure your code so that a global variable is not required. For example:

def upload():
    return [1,2,3,4]

def add():
    numlist = upload()
    for i in numlist:
        print(i)

add()

Upvotes: -1

Related Questions