Python - List Initialization with alternate 0s and 1s

PythonServer Side ProgrammingProgramming

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.

 Live Demo

# 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.

raja
Published on 13-Nov-2020 17:47:10
Advertisements