0

I'm trying to return a list my_list created within function make_list to use in the function print_elems.

I keep getting the error

my_list is not defined

for when I ask to print it, after calling "make_list".

What am I doing incorrectly in trying to return "my_list"?

def make_list():
    my_list = []
    print("Enter \"-999\" to return list.")
    x = int(input("Enter a number: "))
    while x != -999:
        my_list.append(x)
        x = int(input("Enter a number: "))
    return my_list

def print_elems(user_list):
    print(user_list, sep=' ')


make_list()
print(my_list)
print_elems(my_list)

2 Answers 2

3

You are trying to access the local variable my_list. You have to use the returned value instead by assigning it to a variable:

some_name = make_list()  # assign function result to variable
print(some_name)
print_elems(some_name)

On a side note, you probably want to slightly modify print_elems:

def print_elems(user_list):
    print(*user_list, sep=' ')

The * unpacks the list and passes its elements to the print function. Otherwise, when passing a single positional argument to print, the sep parameter will never be used.

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

1 Comment

Thanks for the extra info! I was just starting to look into that
1

You need to assign the return of your function to a variable:

tata = make_list()
print(tata)

The variable my_list is destroyed when you leave the scope of your function that defined it. That is why you return it.


See Short Description of the Scoping Rules? and PyTut: Scopes and namespaces

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.