Is there a way to append elements to a list randomly, built in function
ex:
def random_append():
lst = ['a']
lst.append('b')
lst.append('c')
lst.append('d')
lst.append('e')
return print lst
this will out put ['a', 'b', 'c', 'd', 'e']
But I want it to add elements randomly and out put something like this:
['b', 'd', 'b', 'e', 'c']
And yes there's a function random.shuffle() but it shuffles a list at once which I don't require, I just want to perform random inserts only.
If there is supposed to be exactly one of each item
If you are allowing duplicates (as the output indicates)
random.shuffle
is probably the best tool for the job. It is simple, obvious, and well-named—it's probably more readable than the other suggestions you will get. Additionally, using it is O(n), but usinginsert
(an O(n) operation) n times is quadratic.If you need to perform single insert in a random position then the already given trivial exapmle works:
However if you need to insert k items to a list of length n then using the previously given function is O(n*k + k**2) complexity. However inserting multiple items can be done in linear time O(n+k) if you calculate the target positions ahead of time and rewrite the input list in one go: