Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 I created a function that generate a list but the list is empty in a new .py file
#1
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
Quote
#2
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)
newbieAuggie2019 likes this post
Quote
#3
Thanks a lot Gribouillis, exactly what I was after.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  extract first and last 5 elements from given list and generate a new list. Raj_Kumar 1 84 Dec-07-2019, 05:03 PM
Last Post: ichabod801
  item = index position - list of list RavCOder 9 140 Dec-02-2019, 05:24 PM
Last Post: ThomasL
  List Comprehension - Creating a list of the length of an item help paul41 2 162 Nov-18-2019, 10:21 AM
Last Post: perfringo
  Details of attachment files in a msg file such as file names save into a python list klllmmm 2 162 Nov-12-2019, 05:59 AM
Last Post: klllmmm
  Writing list as a file, then reading that file as a list Zoastria_Balnala 3 170 Oct-17-2019, 07:54 PM
Last Post: Zoastria_Balnala
  How do you replace a word after a match from a list of words in each line of a file? vijju56 1 202 Oct-17-2019, 03:04 PM
Last Post: baquerik
  Question about list and while function doug2019 6 266 Oct-12-2019, 03:07 AM
Last Post: doug2019
  List and function while and else doug2019 3 143 Oct-08-2019, 07:27 PM
Last Post: ichabod801
  How to read a text file into a list or an array musouka 2 288 Oct-07-2019, 01:54 PM
Last Post: musouka
  Inspect.getmembers with isclass returns an empty list Aldar 1 122 Oct-02-2019, 01:48 PM
Last Post: Aldar

Forum Jump:


Users browsing this thread: 1 Guest(s)