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?
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.
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.
Python int() The int() method converts any string, bytes-like object or a number to integer and returns.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With