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.
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]
- Python | Interval Initialization in list
- Python | Boolean list initialization
- Python - Custom dictionary initialization in list
- Python | Alternate Cycling in list
- Python | Add element at alternate position in list
- Python | Alternate range slicing in list
- Python | Multiplying Alternate elements in List
- Python | Alternate element summation in list
- Python - Alternate Minimum element in list
- Python - Repeat Alternate Elements in list
- Python | List consisting of all the alternate elements
- Python | Maximize alternate element List
- Python | Alternate Sort in String list
- Python | Sort alternate numeric and alphabet list
- Python | Increasing alternate element pattern in list
- Python - K Matrix Initialization
- Counters in Python | Set 1 (Initialization and Updation)
- Python - Incremental value initialization in Dictionary
- Python - Incremental K sized Row Matrix Initialization
- Python - Incremental Range Initialization in Matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.