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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Custom Cycle list
# using dropwhile() + cycle() + islice()
import itertools
  
# initialize list
test_list = [3, 4, 5, 7, 1]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initialize element for start cycle
K = 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 result
print("The cycled list is : " + str(res))

chevron_right


Output :

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]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.