Python Forum

Full Version: I created a function that generate a list but the list is empty in a new .py file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys,

newbie to Python, pardon me if my question is subject doesn't make sense.

I created a function to generate a random list of numbers and list is called a.

def generaterandlist():
    import random

    a=[]
    b=1
    ##l = random.randint(0,10)
    ##print(l)

    for x in range(0,4):
        l = random.randint(0,10)
        a.append(l)
        
    print("These are the random list generated %s" % a)    
        
generaterandlist()
I then opens up a new .py file and calls the function which generates the list:
import generaterandlistfile
print(a)
but it says "NameError: name 'a' is not defined".
I understand the reason is I have not defined the list 'a', but I thought since 'a' is defined in the function already, and then the list was created by the function as 'a', I would expect the random number s to already created and stored in 'a'.

My intention is to use the function to create a list, and then call the function from another file and use the list to do something else..

Thanks guys,

Hope the question make sense
Use this
# generaterandlistfile.py
import random

def generaterandlist():
    a=[]
    b=1
    ##l = random.randint(0,10)
    ##print(l)
 
    for x in range(0,4):
        l = random.randint(0,10)
        a.append(l)
    return a # <---- See the return statement here?
Then use it
import generaterandlistfile as glf

spam = glf.generaterandlist()
print(spam)
Thanks a lot Gribouillis, exactly what I was after.