bwrr bwrr - 3 months ago 11
Python Question

Slicing every nth range within a list with a for and a while loop

So I have a short list called someList with some numbers in it. What I want to do is output every 3 elements of the list while iterating over it every 3rd slice range.

So if I have

someList = [1,2,3,4,5,6,7,8,9,10]


The output of my someList should be like this

[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]


Here is my code where I have defined a new temp list to store the output values

someList = [1,2,3,4,5,6,7,8,9,10]
lookupRange = 3
temp = []
for index,i in enumerate(someList):
while index <= len(someList):
temp.append(someList[index:index+lookupRange])
index += 1

print(temp)


However upon running this code I get some rather unexpected results...

[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10], [10], [], [2, 3, 4, 5, 6, 7, 8, 9, 10], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [8, 9, 10], [9, 10], [10], [], [9, 10], [10], [], [10], []]


As you can see, for the first few lines, I do indeed get the desired output with slice range period of 3. But after that it just goes crazy...

Any ideas on whats going wrong here?

PS:I know there are probably simpler one liner ways to do this (such as the numpy.convolve function), but this problem in particular requires I do it with just for and while loops.

Answer

You have nested loops, but you only need one loop.

someList = [1,2,3,4,5,6,7,8,9,10]
lookupRange = 3
temp = []
for index in range(len(someList) - lookupRange + 1):
    temp.append(someList[index:index+lookupRange])