0

Say I have a list like a = ["dog", "cat", "house", "mouse", "goose"]. If I want to start a for loop at a[3] and end it at a[2], how can I do that? a[3:2] of course returns an empty list, so I can't iterate on that. Is there a more pythonic way to do that than iterating overa[3:]+a[:3]?

To be clear, what I want is to have a for loop that starts at a[n], then goes to a[n+1], a[n+2] etc until the end of the list; then, when the last element of the list is reached, the loop continues from a[0] and goes on until a[n-1] (the same thing that I obtain with a[3:]+a[:3]).

a_gdevr
  • 93
  • 7

2 Answers2

2

You can do something like that:

a = ["dog", "cat", "house", "mouse", "goose"]

print(a[3:2:-1])

And the output will be:

['mouse']

Obviously if you want to include the index 2 you have to write a[3:1:-1] (the final index it's not included as always)


UPDATE: after you have updated the request, this should be what you want

a = ["dog", "cat", "house", "mouse", "goose"]

print(a[3:] + a[:3])

The output will be:

['mouse', 'goose', 'dog', 'cat', 'house']
lorenzozane
  • 1,214
  • 1
  • 5
  • 15
0

When you slice a list like that (using a[3:-1]), the last item is non-inclusive. Therefore, if you elements want up to but not including the last element, then -1 should work for you. if you want up to but not including the last 2 elements, then -2 would work here.

e.g, for:

a = ["dog", "cat", "house", "mouse", "goose"]
a[3:-1]

output will be: ["mouse"].

Remember that the index of the list starts at 0. so your list has elements with index from 0 to 4. Printing from the 3rd till the penultimate elements is simply printing the 3rd element as it is the penultimate element too.

Fraf
  • 13
  • 2