Jahigs
Jahigs

Reputation: 45

Returning list from one function to another

I am trying to return New_List to main() and print it out. The end goal is to assign New_List to FirstList after it has been sent through change_list. What am I doing wrong? Getting NameError: name "New_List" is not defined

from __future__ import print_function
import random
def main():
    FirstList = []
    print("Here is the list of random integers...")
    for x in range(0,12):
        FirstList.append(random.randint(50,100))
    for x in FirstList:
        print(x,end=" ")
        if x == FirstList[4]:
            FourthElm = FirstList[3]
        if x == FirstList[4]:
            NinthElm = FirstList[9]
    print(f"\nThe 4th Element in the list is {FourthElm}")
    print(f"The Element at index 9 is {NinthElm}")
    print(f"The smallest element in the list is {min(FirstList)}")
    change_list(FirstList)
    print(New_List)

    


def change_list(x):
    New_List = x[3:9]
    print(f"The size of the list is now {len(New_List)}")
    New_List = sorted(New_List)
    return New_List
    
main()

Upvotes: 1

Views: 58

Answers (2)

Marc Karam
Marc Karam

Reputation: 463

New_List only exists within the change_list function. When you call print(New_List), Python doesn't know where to find it. You'll want to look into Scope.

At this point you have 2 options to change your code:

Option 1

change_list(FirstList)
print(FirstList)

Option 2:

New_List = change_list(FirstList)
print(New_List)

Upvotes: 0

Moon President
Moon President

Reputation: 98

You need to replace change_list(FirstList) with New_List = change_list(FirstList). If you don't assign a variable, it doesn't exist in the scope of the function you try to call it in.

Upvotes: 2

Related Questions