I'm looking for a function that would take a list such as [a,b,c,d] and output a list of all the permutations where adjacent indices are swapped i.e. [[b,a,c,d], [a,c,b,d],[a,b,d,c], [d,b,c,a]]
Thanks
I'm looking for a function that would take a list such as [a,b,c,d] and output a list of all the permutations where adjacent indices are swapped i.e. [[b,a,c,d], [a,c,b,d],[a,b,d,c], [d,b,c,a]]
Thanks
Simple way,you can just use a for
loop and swap the adjacent items,tmp=l[:]
will make a shallow copy,and it won't change original list l
.
See more details from What exactly is the difference between shallow copy, deepcopy and normal assignment operation?:
l=['a', 'b', 'c', 'd']
for i in range(len(l)):
tmp=l[:]
tmp[i],tmp[i-1]=tmp[i-1],tmp[i]
print tmp
Result:
['d', 'b', 'c', 'a']
['b', 'a', 'c', 'd']
['a', 'c', 'b', 'd']
['a', 'b', 'd', 'c']