Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a list from another python file

Tags:

python

I just started programming in Python so I would love a detailed explanation. Let's say I have a list of words at file number 1:

list=["leaf","cream","pickles","vinegar","gouda","almond","fire","orbit","spider","symbol"]

In a cache called "Random Words".

Now I'm coding a different file (file 2) called "The Selected Word". I want to import a different word from file 1 each time I run file 2. What command should I write? I tried this:

word = random.choice.open("random words","w")
print(word)

And it didn't work ...

like image 613
yuval Avatar asked Jun 17 '26 15:06

yuval


2 Answers

to make things simple make sure randomwords.py and theselectedword.py are in the same folder and directory. in randomwords.py

list_of_words = ['age','body',.... etc]
#do not use 'list' to name a variable or object,so as not to override the list function called list()

then in theselectedword.py

from randomwords import list_of_words

import random
word = random.choice(list_of_words)
print(word)
like image 65
Christopher_Okoro Avatar answered Jun 20 '26 04:06

Christopher_Okoro


You could use Pythons module system for this task:

Save list in python script, "Random_Words.py":

my_list = ["leaf"
           , "cream"
           , "pickles"
           , "vinegar"
           , "gouda"
           , "almond"
           , "fire"
           , "orbit"
           , "spider"
           , "symbol"
            ]

And now import this script as a module in the other program, "The_Selected_Word.py":

from Random_Words import my_list

word = random.choice(my_list)
print(word)
like image 45
Gustav Rasmussen Avatar answered Jun 20 '26 04:06

Gustav Rasmussen



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!