3

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.

Ian
  • 30,182
  • 19
  • 69
  • 107
Mars Lee
  • 1,845
  • 5
  • 17
  • 37

2 Answers2

5

An empty list is like 0; no matter what you multiply it by, the answer is still an empty list.

>>> [] == []*8
True

And [][x] will raise an IndexError for any value x.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Wow! I got it! THis is super clear! So if I want to give the empty list value, the only way is .append? I am really appreciate for your answering ;) – Mars Lee Mar 08 '16 at 02:45
  • Yes, an empty list is like any other list; it just doesn't have any values. You can take its length with len (and like any other list, a valid index `i` is `0 <= i < len([]) == 0`-- and there are no integers that are greater than or equal to 0 *and* less than 0), append to it (`l = []; l.append(3); l == [3]`), etc. – chepner Mar 08 '16 at 18:30
1

There is a difference between [None] and []. [None] is a list with one member, which is None. But [] is an empty list with zero member.

When you do [None] * input_num you create a new list with None members, as many as input_num times.

But when you do [] * input_num, there is no member to begin with. Thus you still have an empty list which naturally cannot be indexed.

Ian
  • 30,182
  • 19
  • 69
  • 107
  • Thank you for your help! But can I use .append to give the empty list value? – Mars Lee Mar 08 '16 at 02:50
  • @MarsLee it is good to see you [again](http://stackoverflow.com/questions/35837794/can-someone-explain-this-recursive-for-me). ;) Yes, an empty list is a *list* and thus you may append it with an item, like any other list does – Ian Mar 08 '16 at 02:51
  • Definitely! Thank you for helping me yesterday! I totally understood it! Thank you :) – Mars Lee Mar 08 '16 at 02:53
  • @MarsLee great. ;) yes, it is as you said, we meet again shortly... have a good day! – Ian Mar 08 '16 at 02:56
  • I believe we will meet soon again, since I still have a lot of problems haha. Hope you have a lovely day :) – Mars Lee Mar 08 '16 at 02:57