Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I swap items in a Python list?

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:

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)

And it worked perfectly. But then thanks to the free time that I did have, I modified it a bit and wrote this 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)

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.

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.

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.

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!!

like image 376
thisisashwani Avatar asked Mar 15 '26 03:03

thisisashwani


2 Answers

First question:

This is the reason:

def swap(x,y):
    x, y = y, x

This just swaps the local names. x will then equal y, and vice versa, but only inside that function. Outside that function (global scope), nothing will change.


Second question (you should really avoid asking multiple questions in one question):

Assuming:

x = a[i]
y = a[n]

To swap values in a list, you must set them:

a[n] = x
a[i] = y

Which is that same as:

a[i], a[n] = y, x

And since y = a[n] and x = a[i], it is the same as:

a[i], a[n] = a[n], a[i]
like image 90
matsjoyce Avatar answered Mar 16 '26 15:03

matsjoyce


The swap function is swapping the local variables x and y and not the global array.

def swap(x,y):
  x,y=y,x 

This is completely wrong

You can instead do the following

  • Change the function body to

    return y,x and call the function as a[n],a[i] = swap(a[i],a[n])

  • Or directly swap in-place a[n],a[i] = a[i],a[n]

  • Or do it as you had done earlier
like image 23
Bhargav Rao Avatar answered Mar 16 '26 16:03

Bhargav Rao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!