list reversal error

Joel Goldstick joel.goldstick at gmail.com
Thu Mar 3 18:13:59 EST 2016


On Thu, Mar 3, 2016 at 6:08 PM, John Gordon <gordon at panix.com> wrote:

> In <8b3d06eb-0027-4396-bdf8-fee0cc9ff771 at googlegroups.com>
> vlyamtsev at gmail.com writes:
>
> > i have list of strings "data" and i am trying to build reverse list data1
> > data1 = []
> > for i in range(len(data)):
> >    j = len(data) - i
> >    data1.append(data[j])
>
> > but i have the following error:
> > data1.append(data[j])
> > IndexError: list index out of range
> >
> > am i doing it wrong?
> > Thanks
>
> Python lists are zero-indexed, meaning a list of five items will have
> indexes 0 to 4.
>
> The first time through your loop, i is 0, so
>
>     j = len(data) - i
>
> evaluates to
>
>     j = len(data)
>
> which would yield 5 for a five-element list, but the last actual element
> is in data[4].
>

>>> s = "123"
>>> s2 = s[::-1]
>>> s2
'321'
>>>

Use reverse slice

>
> --
> John Gordon                   A is for Amy, who fell down the stairs
> gordon at panix.com              B is for Basil, assaulted by bears
>                                 -- Edward Gorey, "The Gashlycrumb Tinies"
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Joel Goldstick
http://joelgoldstick.com/ <http://joelgoldstick.com/stats/birthdays>
http://cc-baseballstats.info/



More information about the Python-list mailing list