Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function squaring 2-d array python

Tags:

python

list

I have a function that takes in any 2-d array and return a 2-d array (the same format as the array being implemented) but the values are squared. i.e [[1,2],[3,4]] -----> [[1,4],[9,16]]

my code so far:

m0 = [[1,2],[3,4]]
empty_list = []
for x in m0:
   for i in x:
     empyt_list.append(x**2)

This gives me a 1-d array but how would i return a 2-d array as the imputed value?

like image 817
clumbzy1 Avatar asked Sep 20 '26 14:09

clumbzy1


1 Answers

You can make a recursive function to handle any depth of nested lists:

def SquareList(L):
    if type(L) is list:
        return [SquareList(x) for x in L]
    else:
        return L**2

Example:

 > print(SquareList([1,[3],[2,[3]],4]))
 [1, [9], [4, [9]], 16]
like image 125
Eugene Sh. Avatar answered Sep 22 '26 03:09

Eugene Sh.