Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle through list starting at a certain element

Tags:

python

list

cycle

Say I have a list:

l = [1, 2, 3, 4]

And I want to cycle through it. Normally, it would do something like this,

1, 2, 3, 4, 1, 2, 3, 4, 1, 2...

I want to be able to start at a certain point in the cycle, not necessarily an index, but perhaps matching an element. Say I wanted to start at whatever element in the list ==4, then the output would be,

4, 1, 2, 3, 4, 1, 2, 3, 4, 1...

How can I accomplish this?

like image 296
john Avatar asked Jan 20 '12 11:01

john


People also ask

How do you start a list at a certain point in Python?

We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.

How do you cycle through a list in Python?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.


2 Answers

Look at itertools module. It provides all the necessary functionality.

from itertools import cycle, islice, dropwhile  L = [1, 2, 3, 4]  cycled = cycle(L)  # cycle thorugh the list 'L' skipped = dropwhile(lambda x: x != 4, cycled)  # drop the values until x==4 sliced = islice(skipped, None, 10)  # take the first 10 values  result = list(sliced)  # create a list from iterator print(result) 

Output:

[4, 1, 2, 3, 4, 1, 2, 3, 4, 1] 
like image 169
ovgolovin Avatar answered Sep 30 '22 13:09

ovgolovin


Use the arithmetic mod operator. Suppose you're starting from position k, then k should be updated like this:

k = (k + 1) % len(l)

If you want to start from a certain element, not index, you can always look it up like k = l.index(x) where x is the desired item.

like image 42
Sufian Latif Avatar answered Sep 30 '22 14:09

Sufian Latif