'TypeError: 'int' object is not iterable -- Python map function
I am learning the map function right now. I am creating a function where we can add 2 in all the elements of a list and then print them in a terminal:
def add_twoineach(a):
for i in a:
i = i + 2
print(i)
Till here it is all good.
I am trying to use map function to iterate through a list and add 2 to each of the element of a list:
y = list(map(add_twoineach, (1, 2, 3)))
but I am getting error:
for i in a:
TypeError: 'int' object is not iterable
Solution 1:[1]
It might help to think in terms of types. Python plays fast and loose with types, so let's have an example in a language that both is strict with its typing and uses map idiomatically -- Haskell.
The only bits of syntax that you might need to know is to read :: as "has type of."
addTwo :: int -> int -- takes an int and returns an int
addTwo x = x+2
-- this can also be written as addTwo = (+2), but don't worry about that
addTwoMany :: [int] -> [int] -- takes a list of ints and returns a list of ints
addTwoMany xs = map addTwo xs
as you can see, map takes a function that acts on a single value and instead acts on a whole list of values. This concept generalizes beyond lists to a group in Category Theory called "functors," where you take a function that acts on a single value and make it act on a group of those values instead.
Solution 2:[2]
When using map, you do not need the for loop anymore as the map applies the function on your iteration
def add_twoineach(a):
i = a + 2
return i
y = list(map(add_twoineach, (1, 2, 3)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adam Smith |
| Solution 2 | Tomerikoo |
