0

I'd like a minor clarification of the topic at: How to slice a list from an element n to the end in python?

I want to slice a list inside a loop, so that the last iteration of the loop includes the last element of the list. The only way I've found to do this so far (based on the answers in the other thread) is as follows:

>>> x = list(range(1,11))
>>> for i in range(0,4):
...     x[i:-3+i if -3+i != 0 else None]

The values of x that I expect in each iteration are:

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

It works, but is my solution really the most Python-esque way to accomplish this?

Prune
  • 76,765
  • 14
  • 60
  • 81
  • You might also be interested in: https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator – Patrick Haugh Jul 17 '18 at 17:13
  • 1
    FYI, the word is "Pythonic". – Barmar Jul 17 '18 at 17:15
  • 1
    I think using guaranteed positive indices, as in the solutions by Jerrybibo & Prune, is more readable. But if you want to use subtraction I find `or` more readable than a conditional expression in this context: `x[i:i-3 or None]` – PM 2Ring Jul 17 '18 at 17:19

2 Answers2

4

You're going to a lot of trouble for a straightforward task. How about

x[i:i+7]

This gives the same output, and is much easier to read. The difficulty in your original approach seems to be working around the problem of the list end being 1 past element -1, but you can't designate this as element 0. You can fix the problem by using positive indexing alone.

Prune
  • 76,765
  • 14
  • 60
  • 81
0

I'm not exactly sure about what your question is, but I think that using a simpler approach would work as well:

x = list(range(1, 11))
slice_length = 7
number_of_iterations = 4

# All you had to do was to first iterate
for i in range(number_of_iterations):
    # Then slice the list from i to i+7 in your case
    print(x[i:i+slice_length])

# Output:
# [1, 2, 3, 4, 5, 6, 7]
# [2, 3, 4, 5, 6, 7, 8]
# [3, 4, 5, 6, 7, 8, 9]
# [4, 5, 6, 7, 8, 9, 10]
Jerrybibo
  • 1,315
  • 1
  • 21
  • 27