Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

2 Answers

0 votes
by (106k points)

You can use the below-mentioned code to initialize a two-dimensional array in Python:-

abc = [] 

for item in some_iterable:

abc.append(SOME EXPRESSION)

0 votes
by (20.3k points)

Looks like you are trying to index an uninitialized array. You just have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0

w, h = 8, 5;

Matrix = [[0 for x in range(w)] for y in range(h)] 

Now, you can add items to the list like this:

Matrix[0][0] = 1

Matrix[6][0] = 3 # error! range... 

Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1

x, y = 0, 6 

print Matrix[x][y] # prints 3; be careful with indexing! 

But, you can name them as per your wish, I look at it this way to avoid some confusion that could arise with the indexing, if you can use "x" for both the inner and outer lists, and want a non-square Matrix.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 30, 2020 in Python by ashely (50.2k points)

Browse Categories

...