Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'int' object is not iterable in map function

Sorry I'm a newbie python coder. I wrote this code in PyCharm:

lst_3 = [1, 2, 3]

def square(lst):
    lst_1 = list()
    for n in lst:
        lst_1.append(n**2)

    return lst_1


print(list(map(square,lst_3)))

and i have this type of error : TypeError: 'int' object is not iterable. What is the error in my code?

like image 982
Antonio Esposito Avatar asked Nov 13 '17 19:11

Antonio Esposito


People also ask

How do I fix TypeError type object is not iterable?

The Python "TypeError: 'type' object is not iterable" occurs when we try to iterate over a class that is not iterable, e.g. forget to call the range() function. To solve the error, make the class iterable by implementing the __iter__() method.

How do you make an int iterable in Python?

Iterators and Iterator Protocol So, in a gist, __iter__ is something that makes any python object iterable; hence to make integers iterable we need to have __iter__ function set for integers.

What is int object in Python?

Python int() The int() method converts any string, bytes-like object or a number to integer and returns.

How do you make an object iterable in Python?

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.


1 Answers

The issue here is your misunderstanding of what map is doing. Here's a representative example. I've created an "identity" function of sorts which just echoes a number and returns it. I'll map this function to a list, so you can see what's printed out:

In [382]: def foo(x):
     ...:     print('In foo: {}'.format(x))
     ...:     return x
     ...: 

In [386]: list(map(foo, [1, 2, 3]))
In foo: 1
In foo: 2
In foo: 3
Out[386]: [1, 2, 3]

Notice here that each element in the list is passed to foo in turn, by map. foo does not receive a list. Your mistake was thinking that it did, so you attempted to iterate over a number which resulted in the error you see.

What you need to do in your case, is define square like this:

In [387]: def square(x):
     ...:     return x ** 2
     ...: 

In [388]: list(map(square, [1, 2, 3]))
Out[388]: [1, 4, 9]

square should work under the assumption that it receives a scalar.

Alternatively, you may use a lambda to the same effect:

In [389]: list(map(lambda x: x ** 2, [1, 2, 3]))
Out[389]: [1, 4, 9]

Keep in mind this is the functional programming way of doing it. For reference, it would be cheaper to use a list comprehension:

In [390]: [x ** 2 for x in [1, 2, 3]]
Out[390]: [1, 4, 9]
like image 149
cs95 Avatar answered Nov 05 '22 22:11

cs95