Reputation: 89
I want to add elements to an empty list by index. For instance I want to add 4 to the 5th place of list a.
x = 4
a = []
in other languages like C++ I could create an array with 10 indices and all empty at first and then write something like:
a[5] = 4
But I could not find the same in python. I just found insert method which moves the next elements one index in every insertion (right?). This I must really avoid.
Maybe I need to remove one element and then insert another element, I don't know. I really appreciate your help, I am really stuck here.
Upvotes: 3
Views: 1344
Reputation: 16966
If you like Numpy way of doing it, you can use the following
import numpy as np
a= np.empty(5)
Then, you can assign values normally.
a[0]=4
Then you can convert this array into a list using
a= a.tolist()
Upvotes: 3
Reputation: 29680
As @Jakub stated, you can pre-allocate your list with values.
a = [None] * 5
Then, simply use python's list index notation to change an element's value.
a[3] = 31
Upvotes: 4