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

Iterate through every possible range of list

I’m looking for a function that takes in a list, and iterates through every possible range for example:

example = [1,2,3,4] 

for i in a_list[i:j++]:
    # do something

iterates through ranges between 0:j++

  • [1,2]
  • [1,2,3]
  • [1,2,3,4]

and then it iterates through ranges between 1:j++

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

  • [2,3]
  • [2,3,4]

and then it iterates through ranges between 2:j++

  • [3,4]

And so on…

>Solution :

Use nested loops:

>>> example = [1,2,3,4]
>>> for i in range(len(example)):
...     for j in range(i, len(example)):
...         print(example[i:j+1])
...
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[2]
[2, 3]
[2, 3, 4]
[3]
[3, 4]
[4]
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