-2

I would like to create a 2D array look something like this using a loop in python:

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

1's index increase by 1 next row and rest of elements in array is filled 0.

1
  • 1
    I reopened the question because this is not a duplicate to the linked question, despite having a similar title. This question should be closed instead because it is too broad, without a specific question to an attempt. Commented Jun 4, 2019 at 23:35

2 Answers 2

3

P.S: There are several ways to construct such a matrix. This is one way of doing it using for loops as you asked. The matrix you need is called an identity matrix

size = 6
arr = [[0]*size for _ in range(size)] # Initialize 6 lists all with zeros

# Now change the value to 1 on the diagonal enteries
for i in range(size):
    arr[i][i] = 1

print (arr)   

# [[1 0 0 0 0 0]
#  [0 1 0 0 0 0]
#  [0 0 1 0 0 0]
#  [0 0 0 1 0 0]
#  [0 0 0 0 1 0]
#  [0 0 0 0 0 1]]

Alternative 1 using NumPy: Similar to the above case, initialize a 6x6 matrix of zeros using NumPy and then just replace 0 by 1 on the diagonal.

import numpy as np

size = 6
arr = np.zeros((size, size))

for i in range(size):
    arr[i][i] = 1

print (arr)   

Alternative 2

import numpy as np
size = 6
arr = np.eye(size)

Alternative 3

np.identity(6)
Sign up to request clarification or add additional context in comments.

6 Comments

The nested list in alternative 1 is unnecessary and inefficient. for i in range(size): arr[i][i] = 1 would be enough.
@blhsing: So shall I delete it? I just tried to provide several options to give a better perspective
You can improve it instead.
@blhsing : How about now? Thanks for the suggestion :) Appreciated
@blhsing : Oh sorry, I got confused. I see your point. Let me switch back :)
|
1

you can run following code

arr = []
for i in range(6):
    arr.append([])
    for j in range(6):
        if i == j:
            arr[i].append(1)
        else:
            arr[i].append(0)

print(arr)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.