I want to swap consecutive elements in list with a probability. For example, I have this list:
l=[1,2,3,4,5,6,7,8,9,10,11]
I wrote the following code thats swap the consecutive elements
length=len(l) if len(l)%2==0 else len(l)-1
for i in range(0,length,2):
l[i],l[i+1]=l[i+1],l[I]
The above code results in the following :
l=[2,1,4,3,6,5,8,7,10,9,11]
However, what I want to do is to use a probability for the swap. Let's assume the probability of a swap is 50%. So only 50% of time the swap will happen. Any idea how to achieve this?