[Tutor] Example of good use of enumerate()

Peter Otten __peter__ at web.de
Sun Mar 13 10:47:36 EDT 2022

```On 13/03/2022 12:25, Manprit Singh wrote:
>
> On Sun, Mar 13, 2022 at 4:44 PM Manprit Singh <manpritsinghece at gmail.com>
> wrote:
>
>> Dear Sir,
>>
>> Consider an example of printing all elements of a principal diagonal
of a
>> rectangular matrix.
>> lx = [[2, 5, 9, 0],
>>         [3, 8, 1, 5],
>>         [4, 8, 1, 2],
>>         [6, 1, 2, 4],
>>         [3, 1, 6, 7]]
>>
>> for i, nlist in enumerate(lx):
>>      for j, num in enumerate(nlist):
>>          if i==j:
>>              print(num)

I don't like that because you are discarding almost every matrix value here.

> One can solve it like this also:

> mlen = min(len(lx), len(lx[0]))
> for i in range(mlen):
>      print(lx[i][i])

I think the solution above is the best approach.

> What do you suggest ?

You can avoid both range() and len() with

>>> def diag(m):
try:
for i, row in enumerate(m):
yield row[i]
except IndexError:
pass

>>> list(diag(["ab", "cd"]))
['a', 'd']
>>> list(diag(["abc", "def"]))
['a', 'e']
>>> list(diag(["ab", "cd", "ef"]))
['a', 'd']

though I'm not sure I'm seriously suggesting this ;)
```