krypt
krypt

Reputation: 449

Full iteration over a list from a specific index in python

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?

Upvotes: 0

Views: 178

Answers (4)

Irshad Bhat
Irshad Bhat

Reputation: 8709

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

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142116

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.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121446

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

Upvotes: 4

unutbu
unutbu

Reputation: 879231

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']

Upvotes: 2

Related Questions