[Tutor] update a list
dn
PyTutor at DancesWithMice.info
Sun Oct 11 06:18:14 EDT 2020
On 11/10/2020 21:44, Manprit Singh wrote:
> Dear sir ,
>
> Consider a problem where I have to update a list , at even places with
> increment of 1 and at odd places with increment of 2 . Just need to check
> if this can be done in a better way. My solution is given below:
>
> l = [2, 3, 5, 7, 6, 4]
> for i, j in enumerate(l):
> if i % 2 == 0:
> l[i] = j+1
> else:
> l[i] = j+2
>
> the updated list is
>
> [3, 5, 6, 9, 7, 6]
From where are you finding these problems, or what do you intend to do
with the results?
I am not in-favor of updating lists/list-elements in-place because
altering iterables inside their iteration can cause big problems in
certain other scenarios!
Accordingly, I prefer to create a new list (and if necessary, delete the
old one, afterwards).
Remember that you can slice a sequence. Thus, a faster solution is:
>>> l = [2, 3, 5, 7, 6, 4]
>>> new_l = list()
>>> for index in range( 0, len( l ), 2 ):
... new_l.append( l[ index ] + 1 )
... new_l.append( l[ index + 1 ] + 2 )
...
>>> new_l
[3, 5, 6, 9, 7, 6]
>>>
If you insist upon updating-in-place, replace the append()s with:
l[ index ] += 1
Performance comparison:
No integer-division/remainder comparison, no if, and with half(ish) the
number of loops!
--
Regards =dn
More information about the Tutor
mailing list