2

What I'm trying to accomplish here is to generate a matrix of size n x n. Whatever the matrix is, I have to fill in the number 1 from the top-left corner to the bottom-right corner and 0 everywhere else.

def identity(m):
    new_identity = []
    old_identity = m
        for i in range(len(old_identity)):
            new_identity.append(old_list[1])
    return new_identity

For example, if the matrix was 3 then the expected result would be:

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

Or to make it easier to visualize:

[[1, 0, 0],

 [0, 1, 0],

 [0, 0, 1]]
3
  • possible solutions with numpy here
    – 5agado
    Commented May 7, 2014 at 20:39
  • 2
    @Bill, that question deals with comparison, not creation. Commented May 7, 2014 at 23:02
  • 2
    oneliner no numpy: ones = [[0]*i + [1] + [0]*(n-i-1) for i in range(n) ]
    – JLT
    Commented Sep 5, 2017 at 19:56

2 Answers 2

7

where n is the size of the identity to make

def identity(n):
    return [[1 if i==j else 0 for j in range(n)] for i in range(n)]
0
2

This one might not be the most pythonic, but it's faster than the other solution.

def identity(m):
    result = []
    for i in range(m):
        row = [0]*m
        row[i] = 1
        result.append(row)
    return result

On my machine, for a 500x500 matrix, my function takes 3.13 ms to execute, while the python list comprehension solution (that makes m² comparisons) takes 47.48 ms to complete.

Of course, you should use xrange instead of range if you're using python 2.x

Not the answer you're looking for? Browse other questions tagged or ask your own question.