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
  empty json file error mcmxl22 1 96 Jun-17-2020, 10:20 AM
Last Post: buran
  Code with empty list not executing adeana 6 178 Jun-14-2020, 06:07 PM
Last Post: buran
  Add items from one list to list of lists PUP280 5 580 May-05-2020, 03:47 PM
Last Post: PUP280
  Config file entry as list versus string? taziuk 2 218 Apr-25-2020, 12:01 PM
Last Post: ndc85430
  How to generate a log in a list style? wagnergt12 5 234 Apr-22-2020, 12:47 PM
Last Post: buran
  appending list of list glennford49 2 276 Mar-29-2020, 09:33 AM
Last Post: ibreeden
  dot product of a list by a list in a dictionary stored as a value Fraher123 1 236 Mar-25-2020, 06:08 PM
Last Post: deanhystad
  Trouble with list function Eggman72 2 177 Mar-23-2020, 09:36 PM
Last Post: Eggman72
  Need help to make an empty list with possibility to add Arnsol 1 217 Mar-19-2020, 06:08 PM
Last Post: michael1789
  search binary file and list all founded keyword offset Pyguys 4 295 Mar-17-2020, 06:46 AM
Last Post: Pyguys

Forum Jump:


Users browsing this thread: 1 Guest(s)