# 2x3 dimensional list
multidim_list = [
[1,2,3],
[4,5,6],
]
# 2x3x2 dimensional list
multidim_list2 = [
[
[1,2,3],
[4,5,6],
],
[
[7,8,9],
[10,11,12],
]
]
def multiply_list(list):
...
I would like to implement a function, that would multiply all elements in list by two. However my problem is that lists can have different amount of dimensions.
Is there a general way to loop/iterate multidimensional list and for example multiply each value by two?
EDIT1:
Thanks for the fast answers.
For this case, I don’t want to use numpy.
The recursion seems good, and it doesn’t even need to make copy of the list, which could be quite large actually.
Recursion is your friend:
You could just do
isinstance(item, list)instead ofisinstance(item, MutableSequence), but the latter way is more futureproof and generic. See the glossary for a short explanation.