Python | Custom Cycle list
While working with Python lists, we can have a problem in which we need to perform the cycle of lists. This problem looks quite straight forward and has been discussed earlier. But sometimes, we need to perform it’s variations, hence making task challenging. We can have customizations such as elements from which cycling starts and Number of elements in cycle list. Let’s discuss solution to these variation.
Method : Using dropwhile() + cycle() + islice()
This task can be performed using combination of above functions. In this, the elements are dropped till K with dropwhile(), then the cycle can be done using cycle() and islice() is used to restrict the count of elements in list.
# Python3 code to demonstrate working of# Custom Cycle list# using dropwhile() + cycle() + islice()import itertools # initialize listtest_list = [3, 4, 5, 7, 1] # printing original listprint("The original list is : " + str(test_list)) # initialize element for start cycleK = 7 # initialize size of cycle list N = 12 # Custom Cycle list# using dropwhile() + cycle() + islice()res = list(itertools.islice(itertools.dropwhile(lambda i: i != K, itertools.cycle(test_list)), N)) # printing resultprint("The cycled list is : " + str(res)) |
The original list is : [3, 4, 5, 7, 1] The cycled list is : [7, 1, 3, 4, 5, 7, 1, 3, 4, 5, 7, 1]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


