[Tutor] update a list

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 11 07:17:31 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:

> 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]

Ah! Now I understand.
I read "at even places" to mean "places where the data is even"
rather than places where the index is even!

-- 
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




More information about the Tutor mailing list