nested_map#
- ivy.nested_map(fn, x, /, include_derived=None, to_ignore=None, to_mutable=False, _tuple_check_fn=None, _list_check_fn=None, _dict_check_fn=None, shallow=True)[source]#
Apply a function on x in a nested manner, whereby all dicts, lists and tuples are traversed to their lowest leaves before applying the method and returning x. If x is not nested, the method is applied to x directly.
- Parameters:
fn (
Callable
) – The function to map onto x.x (
Union
[Array
,NativeArray
,Iterable
]) – The item to apply the mapped function to.include_derived (
Optional
[Union
[Dict
[str
,bool
],bool
]], default:None
) – Whether to also recursive for classes derived from tuple, list and dict. Default isFalse
.to_ignore (
Optional
[Union
[type
,Tuple
[type
]]], default:None
) – Types to ignore when deciding whether to go deeper into the nest or notto_mutable (
bool
, default:False
) – Whether to convert the nest to a mutable form, changing all tuples to lists. Default isFalse
._tuple_check_fn (
Optional
[Callable
], default:None
) – Placeholder for the tuple check function, do not set this parameter._list_check_fn (
Optional
[Callable
], default:None
) – Placeholder for the list check function, do not set this parameter._dict_check_fn (
Optional
[Callable
], default:None
) – Placeholder for the dict check function, do not set this parameter.shallow (
bool
, default:True
) – Whether to inplace update the input nest or not Only works if nest is a mutable type. Default isTrue
.
- Return type:
Union
[Array
,NativeArray
,Iterable
,Dict
]- Returns:
ret – x following the application of fn to it’s nested leaves, or x itself if x is not nested.
Examples
With
Tuple
inputs:>>> x = ([[1., 2.], [3., 4.]]) >>> function = lambda a : a * 2 >>> ivy.nested_map(function, x) [[2.0, 4.0], [6.0, 8.0]] >>> print(x) [[2.0, 4.0], [6.0, 8.0]]
With
Dict
input:>>> x = {1 : [1, [2, 3]], 2: (4, 5)} >>> function = lambda a : a + 1 >>> ivy.nested_map(function, x) {1 : [2, [3, 4]], 2: (5, 6)} >>> print(x) {1 : [2, [3, 4]], 2: (5, 6)}
With
List
inputs:>>> x = [['a', 'b', 'c'], ... ['d', 'e', 'f'], ... ['g', ['h', 'i']]] >>> function = lambda a: a + 'H' >>> ivy.nested_map(function, x) [['aH','bH','cH'],['dH','eH','fH'],['gH',['hH','iH']]] >>> print(x) [['aH','bH','cH'],['dH','eH','fH'],['gH',['hH','iH']]]
With
ivy.Container
input:>>> x = ivy.Container( ... a=ivy.array([[1, 2, 3], [9, 8, 7]]) , b=ivy.array([[4, 5, 6], [12, 13, 14]]) ... ) >>> function = lambda a : a + 1 >>> ivy.nested_map(function, x) >>> print(x) { a: ivy.array([[1, 2, 3], [9, 8, 7]]), b: ivy.array([[4, 5, 6], [12, 13, 14]]) }
>>> nest = ([1, 2], [3, 4], [5, 6], {"a": 1, "b": 2, "c": 3}) >>> function = lambda a : a * 2 >>> ivy.nested_map(function, nest, to_ignore=list) ([1, 2, 1, 2], [3, 4, 3, 4], [5, 6, 5, 6], {'a': 2, 'b': 4, 'c': 6})
>>> nest = ([23, 25, 1337], [63, 98, 6]) >>> function = lambda a : a + 1 >>> ivy.nested_map(function, nest, to_mutable=True) [[24, 25, 1338], [64, 99, 7]]