Antonio Esposito
Antonio Esposito

Reputation: 301

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?

Upvotes: 5

Views: 11494

Answers (1)

cs95
cs95

Reputation: 402263

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]

Upvotes: 8

Related Questions