-2

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???

SM Abu Taher Asif
  • 2,221
  • 1
  • 12
  • 14

1 Answers1

1

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.

Amit
  • 2,018
  • 1
  • 8
  • 12