5

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?

4
  • I see the code you posted has a strange indentation, can you fix that? Commented Nov 13, 2017 at 19:44
  • map has a function operate on each element - a scalar in your case. Commented Nov 13, 2017 at 19:44
  • 3
    When you map square to lst_3, each number is passed to square in turn. You don't need to iterate over a number. Commented Nov 13, 2017 at 19:45
  • You can do list(map(lambda x: x**2, lst_3)) Commented Nov 13, 2017 at 19:46

1 Answer 1

8

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.