[Tutor] Example of good use of enumerate()

Alan Gauld alan.gauld at yahoo.co.uk
Sun Mar 13 08:14:27 EDT 2022

```On 13/03/2022 11:25, Manprit Singh wrote:
>   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 ?
>
Personally, I prefer this version because I think it
more clearly expresses the intent.
It is also much more efficient since it doesn't
access every member of the matrix.

And the enumerate version comes second but has the efficiency issue.

The indexing version is just horrible and also potentially error prone.

> 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
>>
>>
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

```