Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Index specific cyclic iteration in list
In this tutorial, we will learn how to cyclically iterate through a list starting from a specific index. Cyclic iteration means when we reach the end of the list, we continue from the beginning until all elements are visited.
Algorithm Steps
- Initialize the list and starting index
- Find the length of the list using
len() - Iterate over the list using the length
- Find the current element index using
(start_index + i) % length - Print the element at that index
Example
Let's implement cyclic iteration starting from index 5 ?
# initializing the list and starting index
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
start_index = 5
# finding the length
length = len(alphabets)
# iterating over the list cyclically
for i in range(length):
# finding the index of the current element
element_index = (start_index + i) % length
# printing the element
print(alphabets[element_index], end=' ')
print() # new line after output
The output of the above code is ?
f g h a b c d e
How It Works
The modulo operator % ensures cyclic behavior. When (start_index + i) exceeds the list length, it wraps around to the beginning:
- Index 5: 'f' (5 % 8 = 5)
- Index 6: 'g' (6 % 8 = 6)
- Index 7: 'h' (7 % 8 = 7)
- Index 8: 'a' (8 % 8 = 0) ? wraps to beginning
- Index 9: 'b' (9 % 8 = 1)
Alternative Approach Using itertools.cycle
Python's itertools.cycle() provides a more elegant solution ?
import itertools
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
start_index = 5
# create cyclic iterator starting from specific index
rotated_list = alphabets[start_index:] + alphabets[:start_index]
cyclic_iter = itertools.cycle(rotated_list)
# print first 8 elements
for i in range(len(alphabets)):
print(next(cyclic_iter), end=' ')
print() # new line
f g h a b c d e
Conclusion
Cyclic iteration from a specific index is achieved using the modulo operator % to wrap indices. This technique is useful for circular data structures and rotating sequences.
Advertisements
