Python: Iterating lists with different amount of dimensions, is there a generic way?
Question:
# 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.
Answers:
Recursion is your friend:
from collections import MutableSequence
def multiply(list_):
for index, item in enumerate(list_):
if isinstance(item, MutableSequence):
multiply(item)
else:
list_[index] *= 2
You could just do isinstance(item, list)
instead of isinstance(item, MutableSequence)
, but the latter way is more futureproof and generic. See the glossary for a short explanation.
numpy arrays do that out of the box.
You can make use of numpy:
import numpy as np
arr_1 = np.array(multidim_list)
arr_2 = np.array(multidim_list2)
Result:
>>> arr_1*2
array([[ 2, 4, 6],
[ 8, 10, 12]])
>>> arr_2*2
array([[[ 2, 4, 6],
[ 8, 10, 12]],
[[14, 16, 18],
[20, 22, 24]]])
# 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:
from collections import MutableSequence
def multiply(list_):
for index, item in enumerate(list_):
if isinstance(item, MutableSequence):
multiply(item)
else:
list_[index] *= 2
You could just do isinstance(item, list)
instead of isinstance(item, MutableSequence)
, but the latter way is more futureproof and generic. See the glossary for a short explanation.
numpy arrays do that out of the box.
You can make use of numpy:
import numpy as np
arr_1 = np.array(multidim_list)
arr_2 = np.array(multidim_list2)
Result:
>>> arr_1*2
array([[ 2, 4, 6],
[ 8, 10, 12]])
>>> arr_2*2
array([[[ 2, 4, 6],
[ 8, 10, 12]],
[[14, 16, 18],
[20, 22, 24]]])