list reversal error

Gary Herron gherron at digipen.edu
Thu Mar 3 18:15:19 EST 2016


On 03/03/2016 02:51 PM, vlyamtsev at 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




More information about the Python-list mailing list