user8620463
user8620463

Reputation: 43

How do I call a list outside of a function in python?

def start(B):
    wordlist = []

    for w in B:
        content = w
        words = content.lower().split()
        for each_word in words:

            wordlist.append(each_word)
            print(each_word)
            return(wordlist)

When I call list 'wordlist' it returns that there isn't anything inside the list. How do I get the list to be callable outside of the function since it works inside the function.

enter image description here

EDIT: Thank you I have updated the code to reflect the mistake I was making using a print tag instead of a return tag.

Upvotes: 0

Views: 16087

Answers (2)

Nimish Bansal
Nimish Bansal

Reputation: 1759

def start(B):
    wordlist = []

    for w in B:
        content = w
        words = content.lower().split()
        for each_word in words:

            wordlist.append(each_word)
            print(wordlist)
    return wordlist

B=["hello bye poop"]
wordlist=start(B)

Just add return wordlist to the function. Adding a return statement in a function returns the object whenever the function is called appropriately and you can store that returned variable in a global scope variable.

Upvotes: 6

liam
liam

Reputation: 2014

You can use the list that first function creates as an argument for the second function:

def some_list_function():
  # generates list
  return mylist

def some_other_function(mylist):
  # takes list as argument and processes
  return result

some_other_function(some_list_function())

You can use this in the future as reference.

Upvotes: 1

Related Questions