How to get variable from for loop

Viewed 39

I want to iterate over a list, and then pass that variable to another Python file, witch writes that text.

forloop.py:

 class Main:
    def list():
        list = ["a","b","c","d","e","f","g"]
        for i in list:
            print_this_variable = i

That iterates over the list, now i want to print the results in a separate file.

print.py:

from forloop import *
print(print_this_variable)

Thanks for the help.

1 Answers

You can't, the way you've configured things. The variable print_this_variable is local to list and won't be available outside of that method.

Here's one way to structure things (there are a variety of other ways, but your question isn't very clear about what you're actually trying to accomplish):

First, note that list is the name of the Python list data type -- you shouldn't use it as a name for functions or variables. Second, you shouldn't name variables the same as functions, because this will mask the function name and will probably bite you at some point.

So, in forloop.py, let's do this:

class Main:
   def example_function(self):
     data = ["a","b","c","d","e","f","g"]
     for i in data:
       self.print_this_variable = i

That makes print_this_variable an instance variable for Main objects.

In print.py, we could write:

import forloop

# We need to create a Main object
m = forloop.Main()

# The `print_this_variable` attribute isn't available until
# after we # call the `example_function` method.
m.example_function()

# Now we can ask for the instance attribute
print(m.print_this_variable)
Related