AlanH - 1 month ago 11x

Python Question

I have a list that I want to split up in to variable steps sizes. For example, if I have a list from 1 to 100, at the end of each iteration, I would want the output to be:

`[1, 2, 3]`

[4, 5, 6, 7, 8]

[9, 10, 11, 12, ..., 15]

[16, 17, ..., 25]

The length of the first list is 3, then 5, then, 7, then 9.

What I have is this

`lst = list(range(1,101))`

odd = 3

for i in range(0, len(lst), odd):

print(lst[i:i+odd])

odd += 2

I know it does not work, but I don't know what needs to change.

Answer

Since the step size varies, you need a while loop:

```
lst = list(range(1,101))
step = 3
idx = 0
while idx<len(lst):
print(lst[idx:idx+step])
idx += step
step += 2
```

Source (Stackoverflow)

Comments