title: How can I swap items in a Python list?
body: <p>The problem was to write the python code to generate all the permutations of the numbers {1,2,3,...,n}. So, I write this code: </p>
  
  <pre><code>def permute(n):
  
    if n==len(a):
      print a
      return
  
    for i in range(n,len(a)):
      swap(i,n)
      permute(n+1)
      swap(i,n)
  
  
  def swap(x,y):
    a[x],a[y]=a[y],a[x]
  
  a=[1,2,3,4]       #any list 
  permute(0)
  </code></pre>
  
  <p>And it worked perfectly. But then thanks to the free time that I did have, I modified it a bit and wrote this code:</p>
  
  <pre><code>def permute(n):
  
    if n==len(a):
      print a
      return
  
    for i in range(n,len(a)):
      swap(a[i],a[n])           #modification
      permute(n+1)
      swap(a[i],a[n])           #modification
  
  
  def swap(x,y):
    x,y=y,x                     #modification
  
  a=[1,2,3,4]
  permute(0)
  </code></pre>
  
  <p>This time it didn't work. But after then, I read a bit about how the assigning of variables to values is different in python.</p>
  
  <p>But still I would like to know what, according to you, is wrong with the second code, so that I can cross-check and discuss what I think is going wrong! That's my first question.</p>
  
  <p>My second question is how the swapping of values takes place in a python list? Is it something different from what will happen with simple values? Because both the codes above seem to apply so. But I cannot figure out it a way I can make myself understand, plus it further confused me that then how python manipulates its lists. </p>
  
  <p>I am sure there is something in the design of Python language that I don't know about leading to all these confusions. Help me sort them out and if possible, use somewhat picture visualizations. It would be very easy then for me to understand what's going on!! </p>