Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #104002

Re: list reversal error

From Mark Lawrence <breamoreboy@yahoo.co.uk>
Newsgroups comp.lang.python
Subject Re: list reversal error
Date 2016-03-03 23:20 +0000
Message-ID <mailman.171.1457047299.20602.python-list@python.org> (permalink)
References <8b3d06eb-0027-4396-bdf8-fee0cc9ff771@googlegroups.com>

Show all headers | View raw


On 03/03/2016 22:51, vlyamtsev@gmail.com wrote:
> 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

At the first pass through the for loop, j is effectively set to 
len(data).  As Python is indexed from zero this will always take you 
beyond the end of data, hence the IndexError.

>
> am i doing it wrong?
> Thanks
>

You are doing things the difficult way.  First up, using the construct:-

for i in range(len(data)):

is usually not needed in Python.

There is a reversed function 
https://docs.python.org/3/library/functions.html#reversed which will do 
the job for you.

data1 = list(reversed(data))

Or use the slice notation

data1 = data[::-1]

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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