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


Groups > comp.lang.python > #104003

Re: list reversal error

From Gary Herron <gherron@digipen.edu>
Newsgroups comp.lang.python
Subject Re: list reversal error
Date 2016-03-03 15:15 -0800
Message-ID <mailman.172.1457047506.20602.python-list@python.org> (permalink)
References <8b3d06eb-0027-4396-bdf8-fee0cc9ff771@googlegroups.com>

Show all headers | View raw


On 03/03/2016 02:51 PM, 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
>   
> am i doing it wrong?
> Thanks

Look at the values (say with a print) you get from your line
     j = len(data) - i
You'll find that that produces (with a list of 4 elements for example) 
4,3,2,1 when in fact you want 3,2,1,0. Soo you really want
     j = len(data) - i -1


Better yet, use more of Python with
     data1 = list(reversed(data))

Or don't even make a new list, just reverse the original list in place
 >>> L=[1,2,3]
 >>> L.reverse()
 >>> L
[3, 2, 1]

Or even better, if you simply want to iterate through the original list, 
but in reverse order:
     for datum in reversed(data):
         ... whatever with datum ...
which wastes no time actually reversing the list, but simply loops 
through them back to front.


Gary Herron

-- 
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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