Chuck
Chuck

Reputation: 4902

What is a compact way to create a multi-dimensional array with default values?

I need to create a 4-D array, each of size 3, where each final element is a default. I thought I was clever with this.

>>> arr = '-'
>>> for _ in range(4):
...     arr = [arr] * 3
...

It looks like I want the default to look, but more experienced Python devs probably see the problem.

>>> arr
[[[['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']], [['-', '-', '-'], ...
>>> arr[0][0][0][0] = 5
[[[[5, '-', '-'], [5, '-', '-'], [5, '-', '-']], [[5, '-', '-'], ...

Is there a good way to do this that doesn't have the various lists pointing to the same sub-list?

Upvotes: 0

Views: 70

Answers (1)

The Big Kahuna
The Big Kahuna

Reputation: 2110

try

arr = [[[['-' for x in range(3)] for y in range(3)] for z in range(3)] for w in range(3)]

Upvotes: 4

Related Questions