Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - List Initialization with alternate 0s and 1s
In this article, we will learn how to initialize a list with alternate 0s and 1s. Given a list length, we need to create a list where elements alternate between 1 and 0 starting with 1.
Method 1: Using a For Loop
The simplest approach is to iterate through the range and append values based on whether the index is even or odd ?
# initializing an empty list
result = []
length = 7
# iterating through the range
for i in range(length):
# checking if index is even or odd
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)
The output of the above code is ?
[1, 0, 1, 0, 1, 0, 1]
Method 2: Using Slice Assignment
A more efficient approach is to pre-allocate the list and use slice assignment to fill alternate positions ?
import math # initializing the length and list with None values length = 7 result = [None] * length # calculating counts for 1s and 0s ones_count = math.ceil(length / 2) zeros_count = length - ones_count # assigning 1s to even indices and 0s to odd indices result[::2] = [1] * ones_count result[1::2] = [0] * zeros_count # printing the result print(result)
The output of the above code is ?
[1, 0, 1, 0, 1, 0, 1]
Method 3: Using List Comprehension
The most concise approach uses list comprehension with a conditional expression ?
length = 7 # creating list with alternating 1s and 0s using list comprehension result = [1 if i % 2 == 0 else 0 for i in range(length)] print(result)
The output of the above code is ?
[1, 0, 1, 0, 1, 0, 1]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| For Loop | O(n) | O(1) extra | High |
| Slice Assignment | O(n) | O(n) extra | Medium |
| List Comprehension | O(n) | O(1) extra | High |
Conclusion
List comprehension provides the most concise solution for creating alternating 0s and 1s. For beginners, the for loop approach offers better readability and understanding of the logic.
