0

How can I iterate over a list beginning from a specific index.

for example:

lst = ["a", "b", "c", "d", "e", "f"]

I want to start iterating from list(3) which is "d", but I want the iteration to continue over all elements. So it will iterate in this order "d", "e", "f", "a", "b", "c".

Is it possible?

1

4 Answers 4

4

You can use list slicing to build a new list object:

for elem in lst[3:] + lst[:3]:

This is fine for small lists; creating the new list objects (for the slicing and the concatenation result) is cheap enough.

Demo:

>>> lst = ["a", "b", "c", "d", "e", "f"]
>>> for elem in lst[3:] + lst[:3]:
...     print elem, 
... 
d e f a b c
Sign up to request clarification or add additional context in comments.

Comments

2

You could use itertools.cycle to make a cyclic iterator out of the list. Then slice len(seq) elements from the iterator, starting from index 3.

In [573]: seq = ["a", "b", "c", "d", "e", "f"]

In [574]: import itertools as IT

In [575]: list(IT.islice(IT.cycle(seq), 3, 3+len(seq)))
Out[575]: ['d', 'e', 'f', 'a', 'b', 'c']

1 Comment

This also works but since the lists I will use this code for are relatively small I choose Martijn's answer. Thank you!
2

For completeness, (although I'd probably go for Martijn's / unutbu's approaches):

from collections import deque

lst = ["a", "b", "c", "d", "e", "f"]

d = deque(lst)
d.rotate(-3)
for el in d:
    # do something

If you needed to keep rotating the data and iterate over it from the start or reverse from the end, then this will be more efficient. However, it does mean you lose access to being able to directly index into d - since it's effectively a doubly-linked list.

3 Comments

Deques are not an option. The code I am working on iterates over the list until a condition is met. During the iteration I sometimes remove elements from the list. With deque's you can't do this.
@krypt to be fair - that's not exactly obvious from your question... iterating over a list and removing elements also sounds like a recipe for disaster...
Yeah it was not a part of the question. I just wanted to tell why deque's aren't an option. Thank you very much anyway!
1

This can be easily done with modulus(%) operator without using any package:

>>> for i in range(3,3+len(lst)):
...    print lst[i%len(lst)],
... 
d e f a b c

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.