Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python importing an array from a different file

So,I have a main.py and a file.py on file.py I have a function(ex:

def s_break(message):
     words = message.split(" ")

, and an array words. )

When I import the words array into main.py using: from "filename" import words I receive the array empty. Why?

Thank you!

like image 236
Florin Avatar asked Aug 04 '26 04:08

Florin


1 Answers

You need to actually call the s_break function otherwise you'll just get the empty list/array.

test_file.py:

message = 'a sample string this represents'
list_of_words = []

def s_break(message):
    words = message.split(" ")
    for w in words:
        list_of_words.append(w)

s_break(message)    # call the function to populate the list

And then in main.py:

from test_file import list_of_words

print list_of_words

Output:

>>> ['a', 'sample', 'string', 'this', 'represents']
like image 163
smoggers Avatar answered Aug 07 '26 02:08

smoggers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!