简体   繁体   中英

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.

在此处输入图片说明

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM