5

I just tried to learn both list comprehensions and Lambda functions. I think I understand the concept but I have been given a task to create a program that when fed in a positive integer creates the identity matrix. Basically if I fed in 2 it would give me: [[1, 0],[0, 1]] and if I gave it 3: [[1, 0, 0],[0, 1, 0], [0, 0, 1] so list within a list.

Now I need to create this all within a lambda function. So that if I type:

FUNCTIONNAME(x) it will retrieve the identity matrix of size x-by-x.

By the way x will always be a positive integer.

This is what I have so far:

FUNCTIONNAME = lambda x: ##insertCodeHere## for i in range(1, x)

I think I am doing it right but I don't know. If anyone has an idea please help!

NoviceProgrammer
  • 257
  • 1
  • 8
  • 15
  • A `lambda` is **just** a way of defining certain kinds of simple functions in a single expression, without needing to name them. This is mainly useful for using the `lambda` as an argument to another function. If the `lambda` will be given a name immediately, **this defeats the purpose** - just use `def`. – Karl Knechtel Oct 19 '22 at 21:16

3 Answers3

6

How about:

>>> imatrix = lambda n: [[1 if j == i else 0 for j in range(n)] for i in range(n)]
>>> imatrix(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]

1 if j == i else 0 is an example of Python's conditional expression.

codeape
  • 97,830
  • 24
  • 159
  • 188
4

This would be my favorite way to do it:

identity = lambda x: [[int(i==j) for i in range(x)] for j in range(x)]

It takes advantage of the fact that True maps to 1 and False maps to 0.

abeinstein
  • 552
  • 4
  • 11
3

Just for completeness (and to highlight how one really should be doing numerical stuff in python):

import numpy
list_eye = lambda n: numpy.eye(n).tolist()

Of course, in practice you'd probably just be using eye(n) by itself and be working with the numpy arrays.

Henry Gomersall
  • 8,434
  • 3
  • 31
  • 54