Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an element in la list by index without moving others

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.

like image 330
peykaf Avatar asked Dec 20 '25 00:12

peykaf


2 Answers

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
like image 189
Jacob G. Avatar answered Dec 21 '25 13:12

Jacob G.


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()
like image 43
Venkatachalam Avatar answered Dec 21 '25 13:12

Venkatachalam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!