[Tutor] update a list

alexkleider alexkleider at protonmail.com
Sun Oct 11 12:21:18 EDT 2020


‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Sunday, October 11, 2020 4:17 AM, Alan Gauld via Tutor <tutor at python.org> wrote:

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

The above solution breaks down if the length of the list happens to be odd:
Python 3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> m = [2, 3, 5, 7, 6, 4, 9]
>>> new = list()
>>> for index in range(0, len(m), 2):
...   new_m.append(m[index] + 1)
...   new_m.append(m[index + 1] + 1)
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: list index out of range
>>>




More information about the Tutor mailing list