简体   繁体   中英

Python: why does my function return an empty list?

I'm trying to write a function that returns all the strings within in a list.

Uing the isinstance() method and a for loop, I append the strings to a new list and then return the list. However, the list is empty.

Interestingly enough, when I use the same code OUTSIDE a function, the correct items are returned. But inside a function, nothing is returned.

Inside a function:

mylist = [1,2,3,"xxx","bob"]

def check_string(mylist): 
    string_list = []

    for item in string_list: 
        if isinstance(item,str):
            string_list.append(item)

    return string_list

check_string(mylist)

The output is an empty list!!! 

Inside a function: 

mylist = [1,2,3,"xxx","bob"]

string_list = []

for item in mylist: 
    if isinstance(item,str): 
        string_list.append(item)

print(string_list)

And I get ['xxx', 'bob']

The print statement returns the right values, but the function returns nothings. What's the deal???

Little change.

mylist = [1,2,3,"xxx","bob"] 
def check_string(mylist): 
    string_list = [] 
    for item in mylist: 
        if isinstance(item,str):
            string_list.append(item) 
    return string_list

Please let me know if this is what you wanted.

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