Sean Klaus
Sean Klaus

Reputation: 189

Index out of range error which is not supposed to happen

I am trying to get these 4 decimal numbers and convert them into binary and store them into list. and I get index out of range error.. what seems to be the problem? I tried to put them in the list not using for loop too. but didn't work

value = [128, 12, 1, 1]
binary = []
i = 0
for x in value:
    binary[i] = bin(x)
    i += 1

Upvotes: 0

Views: 31

Answers (2)

jorgeh
jorgeh

Reputation: 1767

I think this is what you are looking for:

value = [128, 12, 1, 1]
binary = [bin(x) for x in value]

Upvotes: 1

chepner
chepner

Reputation: 532418

You cannot increase the size of a list by assigning to indices beyond the end of the list. Use the append method instead.

value = [128, 12, 1, 1]
binary = []
for x in value:
    binary.append(x)

(Even better is to use a list comprehension, if possible, although that depends on what you actually do with the value of x before appending to binary. The code you show really simplifies to binary = list(value).)

Upvotes: 2

Related Questions