list reversal error

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Mar 3 18:20:41 EST 2016


On 03/03/2016 22:51, 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

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




More information about the Python-list mailing list