Index Specific Cyclic Iteration in List Python (original) (raw)

Last Updated : 17 Jan, 2025

When working with lists in Python, there may be cases where we need to iterate over a list starting from a specific index in a cyclic manner. For example, given the list [10, 20, 30, 40, 50], we may want to start iterating from index 2 (i.e., 30) and continue iterating in a cyclic manner. There are multiple ways to accomplish this task, which we will explore below.

Using cycle() with range()

This method uses itertools.cycle() to create an infinite iterator over the list and range() to limit the number of iterations. It starts iterating from a given index and cycles through the list.

Python `

from itertools import cycle a = [10, 20, 30, 40, 50]

Starting index

start = 2

Create a cyclic iterator using cycle

cyclic_iter = cycle(a)

Use range to limit the number of iterations

for i in range(start, start + len(a)): print(next(cyclic_iter))

`

**Explanation:

Let's explore some more methods and see how we can index specific cyclic iteration in list.

Table of Content

Using while loop with modulus operator

In this method, we use a while loop to iterate through the list cyclically by using the modulus operator to wrap around once we reach the end of the list.

Python `

a = [10, 20, 30, 40, 50]

Starting index

start = 2

Length of the list

n = len(a)

Counter to track the number of iterations

i = start

While loop to iterate cyclically

while True: print(a[i % n])
i += 1 if i == start + n: break

`

**Explanation:

Using list slicing and concatenation

In this method, we use list slicing to split the list into two parts: one from the start index and the other from the beginning of the list. We concatenate these parts and then iterate through the result.

Python `

a = [10, 20, 30, 40, 50]

Starting index

start = 2

List slicing and concatenation for cyclic iteration

a = a[start:] + a[:start] for item in a: print(item)

`

**Explanation:

Using for loop

This method uses a for loop to iterate over the list while manually adjusting the index using the modulus operator to achieve cyclic iteration.

Python `

a = [10, 20, 30, 40, 50]

Starting index

start = 2

Using for loop to manually adjust the index

for i in range(start, start + len(a)): print(a[i % len(a)])

`

**Explanation: