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?
You can use a list comprehension:
for n is number of rows, and m is the number of column, and foo is the value.
Incorrect Approach: [[None*m]*n]
With this approach, python does not allow creating different address space for the outer columns and will lead to various misbehaviour than your expectation.
Correct Approach but with exception:
It is good approach but there is exception if you set default value to
None
So set your default value properly using this approach.
Absolute correct:
Follow the mike's reply of double loop.
To initialize a two-dimensional array in Python:
You can do just this:
For example:
But this has a undesired side effect:
As @Arnab and @Mike pointed out, an array is not a list. Few differences are 1) arrays are fixed size during initialization 2) arrays normally support lesser operations than a list.
Maybe an overkill in most cases, but here is a basic 2d array implementation that leverages hardware array implementation using python ctypes(c libraries)