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?

3
  • You might also be interested in: stackoverflow.com/questions/6822725/… Commented Jul 17, 2018 at 17:13
  • 1
    FYI, the word is "Pythonic". Commented Jul 17, 2018 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] Commented Jul 17, 2018 at 17:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.