-3

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

Rik
  • 1,870
  • 3
  • 22
  • 35
  • Many people ask a question without writing any code,that will make SO like a coding service,but actually I think this is a good question. It's worth to find a simple Pythonic way to do this. – McGrady Mar 25 '17 at 15:58
  • Yeah I could have written code here but I learned from your solution as I am not an expert pythoner – Rik Mar 25 '17 at 16:25

1 Answers1

1

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']
Community
  • 1
  • 1
McGrady
  • 10,869
  • 13
  • 47
  • 69