Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a list/array by index in Python?

Tags:

python

list

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 #  
like image 511
Joan Venge Avatar asked May 15 '09 16:05

Joan Venge


People also ask

How do you populate an array in Python?

Fill Array With Value With the numpy.fill() function to fill an already existing NumPy array with similar values. The numpy. fill() function takes the value and the data type as input parameters and fills the array with the specified value. We first created the NumPy array array with the np.

Can you index into a list Python?

Note. python lists are 0-indexed. So the first element is 0, second is 1, so on.

How do you create an array from 1 to 100 in Python?

Using the range() function to create a list from 1 to 100 in Python. In Python, we can use the range() function to create an iterator sequence between two endpoints. We can use this function to create a list from 1 to 100 in Python.


1 Answers

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.

like image 152
Adam Rosenfield Avatar answered Sep 23 '22 14:09

Adam Rosenfield