'I am getting 'list' object is not callable error for this code. I need to add zero before each element
a = [1,2,3,4]
newarray = list(map(a,[0,*a]))
print(newarray)
output:
'list' object is not callable error
expected: Add zero to each element in array
Solution 1:[1]
Just use a list comprehension:
out = [[0,x] for x in a]
output: [[0, 1], [0, 2], [0, 3], [0, 4]]
Alternatively, itertools.repeat and zip:
from itertools import repeat
out = list(zip(repeat(0), a))
# or keep a generator
# g = zip(repeat(0), a)
output: [(0, 1), (0, 2), (0, 3), (0, 4)]
strings
as your comment is not fully clear ("prepending the string 0"), in case you really want strings, you can use:
out = [f'0{x}' for x in a]
or
out = list(map('{:02d}'.format, a))
output: ['01', '02', '03', '04']
Solution 2:[2]
Builtin function map expects two arguments: a function and a list.
You wrote your arguments in the wrong order: you passed list a first instead of second.
And the thing you tried to pass as a function is not really a function.
Here is a possible fix by defining a function with def:
def the_function_for_map(x):
return [0, x]
newarray = list(map(the_function_for_map, a))
Here is a possible fix by defining a function with lambda:
newarray = list(map(lambda x: [0, x], a))
And finally, here is a possible fix using a list comprehension instead of map:
newarray = [[0, x] for x in a]
In your particular case, you can also use zip with a list full of zeroes:
newarray = list(zip([0]*len(a), a))
Or zip_longest with an empty list and a default value:
from itertools import zip_longest
newarray = list(zip_longest([], a, fillvalue=0))
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 | |
| Solution 2 | Stef |
