I am getting this error message: TypeError: 'function' object is not iterable

Viewed 269

I am new to python. I am getting this error when I run the below code

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-cdb5a334e110> in <module>
     16 
     17 duplicates_removed = clean_strings
---> 18 duplicates_removed = list(dict.fromkeys(duplicates_removed))
     19 print(duplicates_removed)

TypeError: 'function' object is not iterable

Can someone please point me in the right direction?

code

import re
def remove_punctuation(value):
    return re.sub('[!#?]', '', value)

clean_ops = [str.strip, remove_punctuation, str.title]

def clean_strings(strings, ops):
    result = []
    for value in strings:
        for function in ops:
            value = function(value)
        result.append(value)
    return result

clean_strings(states_1, clean_ops)

duplicates_removed = clean_strings
duplicates_removed = list(dict.fromkeys(duplicates_removed))
print(duplicates_removed)
3 Answers

The error line is

duplicates_removed = clean_strings

You probably want to store the result of the function in duplicates removed. For that you need to do:

duplicates_removed = clean_strings(states_1, clean_ops)

Notice how I "merged" the line before. In your original line, you actually put a function object inside duplicates_removed - it's not the result of the function, yet a the function object itself.

The line clean_strings(states_1, clean_ops) calls to the function, but does not store anywhere the results of the function

I also don't see where you define states_1 in your code, I guess it's before?

clean_strings(states_1, clean_ops) call the function but not saving the return value to any variable.

duplicates_removed = clean_strings just point to the function and not calling it, becuse it not have ()

Fix:

duplicates_removed = clean_strings(states_1, clean_ops)
duplicates_removed = list(dict.fromkeys(duplicates_removed))
print(duplicates_removed)
duplicates_removed = clean_strings
duplicates_removed = list(dict.fromkeys(duplicates_removed))
print(duplicates_removed)

You are passing the reference of the function clean_strings to the dict.fromkeys! ^^

This:

duplicates_removed = clean_strings(states_1, clean_ops)
duplicates_removed = list(dict.fromkeys(duplicates_removed))
print(duplicates_removed)

would resolve the problem :)

Related