Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a two-dimensional array in Python?

I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this:

def initialize_twodlist(foo):     twod_list = []     new = []     for i in range (0, 10):         for j in range (0, 10):             new.append(foo)         twod_list.append(new)         new = [] 

It gives the desired result, but feels like a workaround. Is there an easier/shorter/more elegant way to do this?

like image 274
thepandaatemyface Avatar asked Mar 07 '10 17:03

thepandaatemyface


1 Answers

A pattern that often came up in Python was

bar = [] for item in some_iterable:     bar.append(SOME EXPRESSION) 

which helped motivate the introduction of list comprehensions, which convert that snippet to

bar = [SOME_EXPRESSION for item in some_iterable] 

which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.

Your code follows this pattern twice

twod_list = []                                       \                       for i in range (0, 10):                               \     new = []                  \ can be replaced        } this too     for j in range (0, 10):    } with a list          /         new.append(foo)       / comprehension        /     twod_list.append(new)                           / 
like image 57
Mike Graham Avatar answered Oct 04 '22 04:10

Mike Graham