Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: MRAB Newsgroups: comp.lang.python Subject: Re: list reversal error Date: Thu, 3 Mar 2016 23:20:06 +0000 Lines: 34 Message-ID: References: <8b3d06eb-0027-4396-bdf8-fee0cc9ff771@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de U3XlokQkyDLpF1XnnbiCiQf+fA8SACWvRIWVutu5dYMg== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.002 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'error:': 0.05; 'indexes': 0.09; 'python': 0.10; 'subject:error': 0.11; 'index': 0.13; 'evaluates': 0.16; 'from:addr:mrabarnett.plus.com': 0.16; 'from:addr:python': 0.16; 'from:name:mrab': 0.16; 'indexerror:': 0.16; 'len(data)': 0.16; 'message-id:@mrabarnett.plus.com': 0.16; 'received:192.168.1.4': 0.16; 'received:84.93': 0.16; 'received:84.93.230': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'wrote:': 0.16; 'element': 0.18; 'simpler': 0.22; 'trying': 0.22; 'header:In-Reply-To:1': 0.24; 'header:User-Agent:1': 0.26; 'subject:list': 0.26; 'yield': 0.27; 'actual': 0.28; 'loop,': 0.29; 'received:84': 0.32; 'skip:d 20': 0.34; 'lists': 0.34; 'list': 0.34; 'but': 0.36; 'list,': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'thanks': 0.37; 'doing': 0.38; 'skip:z 10': 0.38; 'received:192': 0.39; 'build': 0.40; 'to:addr:python.org': 0.40; 'your': 0.60; 'john': 0.61; 'email addr:gmail.com': 0.62; 'reverse': 0.66 X-CM-Score: 0.00 X-CNFS-Analysis: v=2.1 cv=bsGxfxui c=1 sm=1 tr=0 a=0nF1XD0wxitMEM03M9B4ZQ==:117 a=0nF1XD0wxitMEM03M9B4ZQ==:17 a=L9H7d07YOLsA:10 a=9cW_t1CCXrUA:10 a=s5jvgZ67dGcA:10 a=IkcTkHD0fZMA:10 a=4RBUngkUAAAA:8 a=pGLkceISAAAA:8 a=ziW_yiKF8zu7EEBRSl4A:9 a=QEXdDO2ut3YA:10 X-AUTH: mrabarnett@:2500 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.6.0 In-Reply-To: X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:104001 On 2016-03-03 23:08, John Gordon wrote: > 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]. > A simpler alternative is to use 'reversed': data1 = list(reversed(data))