[Tutor] Example of good use of enumerate()

Manprit Singh manpritsinghece at gmail.com
Sun Mar 13 07:14:53 EDT 2022


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