Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through list like in sliding window

Tags:

python

How can I implement this kind of iteration similar to sliding window method in python.

Given s = [1, 2, 3, 4, 5, 6]

[1, 2, 3]
   [2, 3, 4]
      [3, 4, 5]    
         [4, 5, 6]
            [5, 6]
               [6]
like image 908
DevEx Avatar asked Jun 03 '14 15:06

DevEx


People also ask

Can you iterate through a list?

In programming, we use lists to store sequences of related data. We often want to perform the same operation on every element in a list, like displaying each element or manipulating them mathematically. To do that, we can use a loop to iterate over each element, repeating the same code for each element.

How do you iterate through values in a list?

We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list. The output would be the same as above.

How do I create a sliding window in Python?

Implement Sliding Window Using GeneratorsThe yield keyword inside a function determines that the function is a generator. This will return a generator object and you could either call next(object) to get the next value or iterator in a for loop.


1 Answers

l = [1, 2, 3, 4, 5, 6]    
for i in range(len(l)):
    print l[i : i+3]

Output

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6]
[6]
like image 147
Cory Kramer Avatar answered Sep 27 '22 23:09

Cory Kramer