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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With