[Tutor] Example of good use of enumerate()

Manprit Singh manpritsinghece at gmail.com
Sun Mar 13 07:25:19 EDT 2022


  Dear Sir,

One can solve it like this also:

lx = [[2, 5, 9, 0],
      [3, 8, 1, 5],
      [4, 8, 1, 2],
      [6, 1, 2, 4],
      [3, 1, 6, 7]]

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

What do you suggest ?

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)
>
> The above use of enumerate() works well. Another solution is also given
> below:
> for i in range(len(lx)):
>     for j in range(len(lx[0])):
>         if i == j:
>             print(lx[i][j])
> also works, but lots of indexing and other operations don't look good and
> effective to me .
>
> Is there any other better solution other than the first one using
> enumerate() ?
> Is this a valid and preferred use case of using enumerate() function ?
>
> Regards
> Manprit Singh
>
>
>


More information about the Tutor mailing list