Python | List Initialization with alternate 0s and 1s
The initialization of list with a single number is a generic problem whose solution has been dealt many number of times. But sometimes we require to initialize the list with elements alternatively repeating K no. of times. This has use cases in M.L or A.I algorithms which require presetting of data in lists. Let’s discuss certain ways in which this problem is solved.
Method #1 : Using list comprehension
In this method, we insert elements in the list alternatively for the specific number of times of each elements’ occurrence. It takes the remainder of sum of counts of both occurrences of elements with particular occurrence of element for cycle computation.
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
The list after initializing : [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0]
Method #2 : Using
itertools.cycle() + itertools.islice()
This is the most pythonic way in which we can perform the cyclic initialization. Slice each of the part of list into the allotted element size in a cyclic manner using
The list after initializing : [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1]