Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List of tuples from original list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading