Ceiun
Ceiun

Reputation: 73

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

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

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

And so on...

Upvotes: 0

Views: 46

Answers (1)

Samwise
Samwise

Reputation: 71434

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]

Upvotes: 4

Related Questions