How to apply a function to a list within a list

  • A+
Category:Languages

I have a list and a function:

t = [3, [1], [2, [1], [1]]]  f = lambda x: x**2 

I want the result like this:

[9, [1], [4, [1], [1]]] 

I tried to use map function but it did not seem to work

I got a type error when I do this:

list(map(f, t)) 


You can use a recursion function and a list comprehension as following:

def nested_pow(arr):     return [pow(i, 2) if isinstance(i, int) else nested_pow(i) for sub in arr]  

Demo:

In [34]: nested_pow(t) Out[34]: [9, [1], [4, [1], [1]]] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: