# 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.
There are multiple ways to iterate over a list in Python. Let’s see all the different ways to iterate over a list in Python, and performance comparison between them. Method #1: Using For loop. Python3. list = [1, 3, 5, 7, 9] for i in list: print(i) Output: 1 3 5 7 9.
There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within lists.
When you combine zip () , for Loops, and tuple unpacking, you can traverse two or more iterables at once. 9. Iterate Through List in Python Using Iterators – Iter () and Next ()
This 2D list also has 3 elements, but each of those elements is a list itself. Let’s build on the list examples above. To iterate through the 1D list [0, 1, 4] and print each element separated by a space, you could use the following code:
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.
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]]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With