Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert elements into the list at arbitrary positions?

Tags:

python

list

I have this

>>> a = [1, 4, 7, 11, 17]

Is there any way to add 4 characters '-' randomly between the other elements to achieve, for example

['-', 1, '-', 4, 7, '-', '-', 11, 17]
like image 774
rikovvv Avatar asked Dec 13 '22 22:12

rikovvv


1 Answers

You could simply do:

import random
for _ in range(4):
    a.insert(random.randint(0, len(a)), '-')

The loop body inserts a '-' at a random index between 0 and len(a)(inclusive). However, since inserting into a list is O(N), you might be better off performance-wise constructing a new list depending on the number of inserts and the length of the list:

it = iter(a)
indeces = list(range(len(a) + 4))
dash_indeces = set(random.sample(indeces, 4))  # four random indeces from the available slots
a = ['-' if i in dash_indeces else next(it) for i in indeces]
like image 113
user2390182 Avatar answered Dec 16 '22 11:12

user2390182