-1
  • How to create increment 2D list

  • if input = 3 then output is

  [ 1,0,0],
  [1,2, 0],
  [1,2,3]]
  • if input = 4 then output is
[[1,0,0,0],
[1,2,0,0],
[1,2,3,0], 
[1,2,3,4]]

Code is below to print every number to Zero

  • How to increment of [x][y]
w = 3
matrix = [[0 for x in range(w)] for y in range(w)] 
matrix

or

rows = 3
cols = 3

matrix = []
for i in range(rows):
  row = []
  for j in range(cols):
    row.append(0)
  matrix.append(row)

print(matrix)
Maws
  • 243
  • 2
  • 6

2 Answers2

2

You could try with a list comprehension:

matrix = [[x + 1 for x in range(y + 1)] + [0] * (w - y - 1) for y in range(w)]
print(matrix)

Output for 3:

[[1, 0, 0], [1, 2, 0], [1, 2, 3]]

Output for 4:

[[1, 0, 0, 0], [1, 2, 0, 0], [1, 2, 3, 0], [1, 2, 3, 4]]

If you want to edit the value of this list in the future, use:

matrix = [[x + 1 for x in range(y + 1)] + [0 for x in range(w - y - 1)] for y in range(w)]

Because multiplying a list creates unexpected modifications for modifying.

More about this here.

Edit:

If you don't want a list comprehension, try:

matrix = []
for y in range(w):
    l1 = []
    for x in range(y + 1):
        l1.append(x + 1)
    l1.extend([0] * (w - y - 1))
    matrix.append(l1)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Using double-comprehension for 2D list:

>>> [list(range(1, i+1))+[0]*(n-i) for i in range(1,n+1)]

OUTPUT:

[[1, 0], [1, 2]] #n=2
[[1, 0, 0], [1, 2, 0], [1, 2, 3]]  #n=3
[[1, 0, 0, 0], [1, 2, 0, 0], [1, 2, 3, 0], [1, 2, 3, 4]] #n=4

Non-comprehension solution:

result = []
for i in range(1, n+1):
    row = list(range(1, i+1))+[0]*(n-i)
    result.append(row)  
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • Just a note that using `*` multiplication of lists will result in unexpected modifications if you modify this list, check [this](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) out for more. – U13-Forward Aug 17 '21 at 05:38
  • 1
    @U12-Forward no, this won't matter here. – juanpa.arrivillaga Aug 17 '21 at 05:40
  • @U12-Forward, Thank you for that reference, yes that's `True` because all the values have the same memory reference in that question. But I don't think that should be problem in this case. – ThePyGuy Aug 17 '21 at 05:40
  • Can you answer without list comprehension also – Maws Aug 17 '21 at 05:42
  • @Maws, you should not have problem to break above comprehension to normal for loop block. – ThePyGuy Aug 17 '21 at 05:44