- 2
How to find the next element in python list?
My_list = [0, 1 , 2, 3] for I in range (Len(My_list)): Print(My_list[I+1], [I]) The output of this code is 1 0 2 1 3 2 indexError: list index out of range I want to get the same output but without the list index out of range. My expected output should look like this: 0 1 2 1 3 2 How can I accomplish this and get the code to run without an error??
8 Answers
+ 6
shorten the range by one
+ 1
Describe how that expected output comes to be will you?
+ 1
You have to write:
(len(My_list)-1)
Because lenght of list is 4, thats too long ;-)
0
Oma Falk that will not work if the first value I input is 1
0
Lothar the example you provided will iterate through 0, 1 , 2, 3
My expected output is to print numbers in pairs(next list element, list element). Can you provide a running example?
0
Karzan
I am confused... what do u want?
https://code.sololearn.com/cJ1y434AZ0Ij/?ref=app
0
,Ipang yes I am taking an input from users.
0
Just reduce the range by one and your indexing error will be sorted.
And do you want the result in below way
01
12
23