Python Forum
I created a function that generate a list but the list is empty in a new .py file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: I created a function that generate a list but the list is empty in a new .py file (/thread-21751.html)



I created a function that generate a list but the list is empty in a new .py file - mrhopeedu - Oct-12-2019

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


RE: I created a function that generate a list but the list is empty in a new .py file - Gribouillis - Oct-12-2019

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)



RE: I created a function that generate a list but the list is empty in a new .py file - mrhopeedu - Oct-12-2019

Thanks a lot Gribouillis, exactly what I was after.