I have a nested list a = [1, 2, [3, 4], 5]
and I want to apply a function that will raise every number to the power of 2. The result will be like this:
You are decomposing your list into its elements -some of them are lists which can not be multiplied with itself ([3,4]*[3,4]
).
Not sure if that is smart - but you can use a "recursing" lambda:
a =[1, 2, [3, 4], 5]
l = lambda x : x * x if isinstance(x,int) else list(map(l,x))
a = list(map(l, a))
print(a)
Output:
[1, 4, [9, 16], 25]
Works also for "deeper" levels:
a =[1, 2, [3, [7,8], 4], 5]
Output:
[1, 4, [9, [49, 64], 16], 25]
but will crash if you mix non-iterables things into the mix