0

Let's say I have a list in python [1, 2, 3, 4, 5, 6, 7, 8, 9]

I'm curious what might be considered the most "pythonic" way to iterate over this list 5 items at a time so the results are:

[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]
[5, 6, 7, 8, 9]
captainKirk104
  • 177
  • 1
  • 3
  • 7

1 Answers1

0

You can use list slicing inside a list comprehension:

s = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_s = [s[i:i+5] for i in range(len(s)-4)]

Output:

[[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102