[Tutor] Example of good use of enumerate()
dn
PythonList at DancesWithMice.info
Sun Mar 13 16:49:50 EDT 2022
On 14/03/2022 01.14, Alan Gauld via Tutor wrote:
> 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.
Agree with the above. However, native Python is probably *not* the
tool-for-the-job!
Python's for-each loops have to be augmented by enumerate(), to revert
to working like for-index loops. (a backward step IMHO)
The reason Python/we don't use the latter in the first place is
illustrated in @Alan's last comment/warning!
You could 'improve' basic-Python by taking to the PSL. For instance:
import itertools as it
list(
it.chain.from_iterable( lx )
)[ 0::min( len( lx ), len( lx[ 0 ] ) )+1 ]
-> [2, 8, 1, 4]
or even, keeping it all in itertools:
list(
it.islice(
it.chain.from_iterable( lx ),
0,
999,
min(
len( lx ),
len( lx[ 0 ] )
)
+ 1
)
)
NB the "999" is a ghastly 'magic number'. OK, it could be replaced by
the order of the matrix, but...
Wouldn't these tasks be better performed by employing a numeric or
matrix-processing library, ie something that has been specifically
designed for the job?
--
Regards,
=dn
More information about the Tutor
mailing list