0

I want to use a list that was created from a previous function in my other function. After a bit of research it seems using return is the way of doing it. However I cannot get it to work. This is my code:

def FunctionA():
  all_comments1 = [1,2,3,4]
  return all_comments1

def FunctionB():
  FunctionA()
  all_comment_string1 = ''.join(all_comments1)
  newlistings1 = all_comment_string1.split('\n')
  print(newlistings1)

def DoSomething():
  FunctionB()

  DoSomething()

It gives me an error:

NameError: name 'all_comments1' is not defined

I want to know how I can define the variable successfully.

  • 1
    You are calling function A but not holding on to its result. Try this in function B: `all_comments1 = FunctionA()` So, this means, you take the return value of FunctionA and assign it to a variable that you can use going forward. – topsail Oct 02 '22 at 15:27
  • Thank you for the fast reply. It worked! @topsail – RonaLightfoot Oct 02 '22 at 15:43

2 Answers2

3

You have to define a new variable. Right now you call the FunctionA() but don't save its return value. To do so, simply make a new variable like so:

def FunctionA():
    all_comments1 = [1,2,3,4]
    return all_comments1

def FunctionB():
    all_comments = FunctionA()
    print(all_comments)

FunctionB()

>> [1,2,3,4]
StreakyFly
  • 41
  • 6
  • I have a related question: What do I do if I need to return 2 variables (or lists) instead of just 1? – RonaLightfoot Oct 02 '22 at 15:55
  • 1
    @RonaLightfoot simply return 2 values and then assign 2 variables instead of one. It's called unpacking variables. Eg. in FunctionA "return var1, var2"; and when you call the function, assign variables like this: "var1, var2 = FunctinA()". Or you can just do "vars = FunctinA()" and then depending on which variable you want, use their index, like so: print(vars[0], vars[1]). – StreakyFly Oct 02 '22 at 19:04
1

I believe you are looking to use global variables between your functions. Modify your code to the following:

def FunctionA():
    # Declare all_comments1 as a global variable
    global all_comments1
    all_comments1 = [1, 2, 3, 4]
    return all_comments1


def FunctionB():
    # Access global variable
    global all_comments1
    # Run functionA otherwise global variable will not be defined
    FunctionA()

    # Map objects from `all_comments1` to str, since they are int
    all_comment_string1 = ''.join(map(str, all_comments1))
    newlistings1 = all_comment_string1.split('\n')
    print(newlistings1)

def DoSomething():
    FunctionB()

DoSomething()

>> ['1234']
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69