[Tutor] update a list

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 11 07:13:36 EDT 2020


On 11/10/2020 09:44, Manprit Singh wrote:

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

Sorry, I don't understand how you got that output.
I'd expect all output numbers to be odd, that is:

[3,5,7,9,7,5]

I think I must be missing some aspect of your problem?

If it's just a typo then I'd probably prefer to use map()

newlist = map(lambda n: n+1 if n%2 else n+2, oldlist)

or a list comprehension

newlist = [n+1 if n%2 else n+2 for n in oldlist]

These both build a new list from the old list so might
not be appropriate for a very large list in which case
your solution is a valid one.

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