1

I'm trying to make a program that will generate a random list, length being determined by user input, that will be sorted. I'm having a problem accessing/passing my randomly generated list to other functions. For example, below, I can't print my list x. I've also tried making a function specifically for printing the list, yet that won't work either. How can I pass the list x?

unsorted_list = []
sorted_list = []

# Random list generator
def listgen(y):
    """Makes a random list"""
    import random
    x = []
    for i in range(y):
        x.append(random.randrange(100))
        i += 1
    return x

def main():
    y = int(input("How long would you like to make the list?: "))
    listgen(y)
    print(x)


main()
1
  • x is local to listgen() Commented Mar 20, 2014 at 17:42

3 Answers 3

2

x = listgen(y)

def main():
    y = int(input("How long would you like to make the list?: "))
    x = listgen(y)
    print(x)

x should be assigned based on return value of your function

Sign up to request clarification or add additional context in comments.

Comments

0
l = listgen(y)
print(l)

The variable x is local to listgen(). To get the list inside of main(), assign the return value to a variable.

Comments

0

In your main, this:

def main():
    y = int(input("How long would you like to make the list?: "))
    listgen(y)
    print(x)

should be:

def main():
    y = int(input("How long would you like to make the list?: "))
    x = listgen(y) # Must assign the value returned to a variable to use it
    print(x)

Does that make sense?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.