Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #103999
| From | John Gordon <gordon@panix.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: list reversal error |
| Date | 2016-03-03 23:08 +0000 |
| Organization | PANIX Public Access Internet and UNIX, NYC |
| Message-ID | <nbag4v$vs$1@reader1.panix.com> (permalink) |
| References | <8b3d06eb-0027-4396-bdf8-fee0cc9ff771@googlegroups.com> |
In <8b3d06eb-0027-4396-bdf8-fee0cc9ff771@googlegroups.com> vlyamtsev@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].
--
John Gordon A is for Amy, who fell down the stairs
gordon@panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
list reversal error vlyamtsev@gmail.com - 2016-03-03 14:51 -0800
Re: list reversal error John Gordon <gordon@panix.com> - 2016-03-03 23:08 +0000
Re: list reversal error Joel Goldstick <joel.goldstick@gmail.com> - 2016-03-03 18:13 -0500
Re: list reversal error MRAB <python@mrabarnett.plus.com> - 2016-03-03 23:20 +0000
Re: list reversal error Mark Lawrence <breamoreboy@yahoo.co.uk> - 2016-03-03 23:20 +0000
Re: list reversal error Gary Herron <gherron@digipen.edu> - 2016-03-03 15:15 -0800
Re: list reversal error Steven D'Aprano <steve@pearwood.info> - 2016-03-04 11:06 +1100
csiph-web