Alex Rivera | Logout

Populating a list/array by index in Python?

Asked 2009-05-15T16:57:25.047
35

Is this possible:

myList = []

myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'

When I try, I get:

# IndexError: list assignment index out of range # 
Edit
Report

1 Answer

61

You'll have to pre-fill it with something (e.g. 0 or None) before you can index it:

myList = [None] * 100  # Create list of 100 'None's
myList[12] = 'a'  # etc.

Alternatively, use a dict instead of a list, as Alex Martelli suggested.

answered 2009-05-15T17:03:29.993

Your Answer