I have a list [6, 63, 131, 182, 507, 659, 669]
and would like to create a new list of pairs that looks like this:
[(7,63),(64,131),(132,182),(183,507),(508,659),(660,669)]
When I use the below code:
list = [6, 63, 131, 182, 507, 659, 669]
line_num = 0
for idx,i in enumerate(list):
print(list[idx]+1,list[idx+1])
I get below error:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
5 pass
6 else:
----> 7 print(city_index[idx]+1,city_index[idx+1])
IndexError: list index out of range
How do I end the loop before I get an error?
>Solution :
Use slicing, and it returns everything of the message but the last element ie :-1
list = [6, 63, 131, 182, 507, 659, 669]
line_num = 0
for idx,i in enumerate(list[:-1]):
print(list[idx]+1,list[idx+1])