Path: csiph.com!feeder.erje.net!2.us.feeder.erje.net!bloom-beacon.mit.edu!bloom-beacon.mit.edu!panix!gordon From: John Gordon Newsgroups: comp.lang.python Subject: Re: list reversal error Date: Thu, 3 Mar 2016 23:08:15 +0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Lines: 34 Message-ID: References: <8b3d06eb-0027-4396-bdf8-fee0cc9ff771@googlegroups.com> NNTP-Posting-Host: panix1.panix.com X-Trace: reader1.panix.com 1457046495 1020 166.84.1.1 (3 Mar 2016 23:08:15 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Thu, 3 Mar 2016 23:08:15 +0000 (UTC) User-Agent: nn/6.7.3 Xref: csiph.com comp.lang.python:103999 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"