0

I have an empty python list. and I have for loop that insert elements with index but at random (means indices are chosen randomly to insert the item). I tried a simple example, with randomly select indices, but it works in some indices but others won't work. Below is a simple example of what I wanna do:

a=[]
#a=[]

a.insert(2, '2')
a.insert(5, '5')
a.insert(0, '0')
a.insert(3, '3')
a.insert(1, '1')
a.insert(4, '4')

The output of this is a = ['0','1','2','5','4','3'] it's correct in the first three (0,1,2) but wrong in the last three ('5','4','3')

How to control insert to an empty list with random indices.

9
  • This will be tricky using an empty list, because when the list is empty and you try to add to, say index 5, it has no meaning because the element will be the first and only element of the list anyway... You might want to initialize the list with some default value, or make sure you padd it with a default value everytime you insert in an index greater than the list's size... Commented May 9, 2020 at 13:51
  • Why do you need to do this? What are you trying to accomplish? Commented May 9, 2020 at 13:53
  • To insert at random position in list you could use a.insert(random.randint(0, len(a)), v) where v is the value to insert. Note with empty list, len(a)=0 so will insert at position 0 as expected. This is from How to insert elements into the list at arbitrary positions? Commented May 9, 2020 at 13:55
  • Do you need to use a list because of some of its other properties/methods? Commented May 9, 2020 at 13:59
  • I don't think there is enough information: without knowing why you need to do this and how the sequence will be used - what problem are you trying to solve? - it isn't possible to suggest an alternate method and the only answer is that using insert the way you have shown won't work. Commented May 9, 2020 at 14:40

3 Answers 3

3

list.insert(i, e) will insert the element e before the index i, so e.g. for an empty list it will insert it as the first element.

Map out the operations in your head using this information:

a = [] # []
a.insert(2, '2') # ['2']
a.insert(5, '5') # ['2', '5']
a.insert(0, '0') # ['0', '2', '5']
a.insert(3, '3') # ['0', '2', '5', '3']
a.insert(1, '1') # ['0', '1', '2', '5', '3']
a.insert(4, '4') # ['0', '1', '2', '5', '4', '3']

Keep in mind that lists are not fixed sized arrays. The list has no predefined size, and can grow and shrink by appending or popping elements.


For what you might want to do you can create a list and use indexing to set the values.

If you know the target size (e.g. it is 6):

a = [None] * 6
a[2] = '2'
# ...

If you only know the maximum possible index, it would have to be done like this:

a = [None] * (max_index+1)
a[2] = '2'
# ...
a = [e for e in a if e is not None] # get rid of the Nones, but maintain ordering

If you do not know the maximum possible index, or it is very large, a list is the wrong data structure, and you could use a dict, like pointed out and shown in the other answers.

Sign up to request clarification or add additional context in comments.

9 Comments

The question is how to do it not why isn't it working.
@wwii There is no way to insert an element into an (empty) list at a fixed position, that's the point. It is the wrong data structure.
@wwii the answer "you can't" will not be very helpful for the OP.
What happens to all of those None's after the items have been randomly inserted.
You could also just process all your data, but return a tuple (index, result), and sort all tuples after the run.
|
1

If your values are unique, could you use them as keys in a dictionary, with the dict values being the index?

a={}
nums = [1,4,5,7,8,3] 

for num in nums:
    a.update({str(num): num})

sorted(a, key=a.get)

2 Comments

This is a good solution if the maximum occurring index is unknown or very large.
Thanks, yes it seems better than a list
1

If you have an empty array and you try to add some element in the third position, that element will be added in first position. Because python's list is a linked list.

You could resolve your problem creating a list with None values in it. This could be made with this:

# Creating a list with size = 10, so you could insert up to 10 elements.
a = [None] * 10
# Inserting the 99 in third position
a.insert(3,99)

Another way to do that is using numpy:

import numpy as np

# Create an empty array with 10 elements
a = np.empty(10,dtype=object)

# Insert 99 number in third position
np.insert(a, 3, 99)

print(a)
# array([None, None, None, 99, None, None, None, None, None, None, None],
#      dtype=object)

3 Comments

What happens to all of those None's after the items have been randomly inserted.
Inserting into numpy arrays will create a new copy of the array every time. It's probably much faster to insert into a list and convert that to an numpy.array once in the end. The tip of using numpy defeats the advantages of using numpy completely.
Thanks, you are right, additionally the time is slower. I fixed my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.