Why does this code raise IndexError in certain situation?

Viewed 64

My function is like this:

input:

8

output:

['000', '001', '010', '011', '100', '101', '110', '111']

So this is to create a list to store input_number binary numbers start from 0. Here is my code (Correct version):

import math

input_num = 8
max_bit = math.ceil(math.log(input_num, 2))

list_Bin = [None] * input_num

for i in range(input_num):
    extra_d = max_bit - len(bin(i)[2:])
    list_Bin[i] = '0'*extra_d + bin(i)[2:]

print(list_Bin)

This code works well. But if I change one line of the code:

list_Bin = [None] * input_num

to

list_Bin = [] * input_num

It will raise IndexError.

I really want to know why, since I have met this problem many times.

2 Answers
Related