[Tutor] update a list
Mark Lawrence
breamoreboy at gmail.com
Sun Oct 11 14:34:58 EDT 2020
On 11/10/2020 11:18, dn via Tutor wrote:
> 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 )
Where is the list slicing above, all I can see is single items in the
old list being used? Using 'range' and 'len' in combination is usually
wrong, 'enumerate' is the preferred solution. It's been pointed out
elsewhere that your solution doesn't work for an odd numbered length of
the initial list, although that has been wrongly attributed to Alan Gould.
> ...
> >>> 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!
No actual measurements to show that this is the case. All I can say is
that in 20 years of using Python my gut instinct for performance has
never once been correct.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list