- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - List Initialization with alternate 0s and 1s
In this article, we are going to learn how to initialize a list with alternate 0s and 1s. We'll have list length and need to initialize with alternate 0s and 1s.
Follow the below steps to initialize a list with alternate 0s and 1s.
- Initialize an empty list and length.
- Iterate length times and append 0s and 1s alternatively based on the index.
- Print the result.
Example
Let's see the code.
# initialzing an empty list result = [] length = 7 # iterating for i in range(length): # checking the index if i % 2 == 0: # appending 1 on even index result.append(1) else: # appending 0 on odd index result.append(0) # printing the result print(result)
If you run the above code, then you will get the following result.
Output
[1, 0, 1, 0, 1, 0, 1]
Let's see another way to initialize the list with 0s and 1s. Follow the below steps to complete the code.
- Initialize list with None's length times.
- Replace the [::2] with 1s and [1::2] with 0s.
- Print the result.
Example
Let's see the code
import math # initializing the length and list length = 7 result = [None] * length _1s_count = math.ceil(length / 2) _2s_count = length - _1s_count # adding 0s and 1s result[::2] = [1] * _1s_count result[1::2] = [0] * _2s_count # printing the result print(result)
If you run the above code, then you will get the following result.
Output
[1, 0, 1, 0, 1, 0, 1]
Conclusion
If you have any queries in the article, mention them in the comment section.
- Related Articles
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Largest subarray with equal number of 0s and 1s in C++
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Count Substrings with equal number of 0s, 1s and 2s in C++
- Boolean list initialization in Python
- Check if a string has m consecutive 1s or 0s in Python
- Segregate all 0s on right and 1s on left in JavaScript
- XOR counts of 0s and 1s in binary representation in C++
- Program to find minimum possible sum by changing 0s to 1s k times from a list of numbers in Python?
- C Program to construct DFA accepting odd numbers of 0s and 1s
- Alternate range slicing in list (Python)
- Alternate element summation in list (Python)
- Encoding a number string into a string of 0s and 1s in JavaScript
- Constructing a string of alternating 1s and 0s of desired length using JavaScript
- Minimum flips to make all 1s in left and 0s in right in C++

Advertisements