- 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??

7th Jul 2021, 6:06 PM
Karzan
8 Answers
+ 6
shorten the range by one
7th Jul 2021, 6:13 PM
Oma Falk
Oma Falk - avatar
+ 1
Describe how that expected output comes to be will you?
7th Jul 2021, 6:17 PM
Ipang
+ 1
You have to write: (len(My_list)-1) Because lenght of list is 4, thats too long ;-)
8th Jul 2021, 5:51 AM
Angela
Angela - avatar
0
Oma Falk that will not work if the first value I input is 1
7th Jul 2021, 6:15 PM
Karzan
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?
7th Jul 2021, 6:22 PM
Karzan
7th Jul 2021, 6:25 PM
Oma Falk
Oma Falk - avatar
0
,Ipang yes I am taking an input from users.
7th Jul 2021, 8:47 PM
Karzan
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
8th Jul 2021, 10:46 AM
Silent