How to create a list of lists where each sub-list 'increments' as follows: [1, 0, 0], [1, 1, 0], [1, 1, 1]

numValues = 12
result = [ [1] * i + [0] * (numValues - i) for i in range(1, numValues+1) ]

You can do this as a nested list comprehension, with two iterators over range(numValues) and only setting a 1 when the second iterator is <= the first:

numValues = 4

outerList = [[1 if j <= i else 0 for j in range(numValues)] for i in range(numValues)]
print(outerList)

Output:

[[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]

If numpy is an option, this can be done very easily with np.tril:

import numpy as np

n=5
out = np.ones((n,n))
np.tril(out)

array([[1., 0., 0., 0., 0.],
       [1., 1., 0., 0., 0.],
       [1., 1., 1., 0., 0.],
       [1., 1., 1., 1., 0.],
       [1., 1., 1., 1., 1.]]) 

Tags:

Python

List