-1

I want to change the position of two lists inside a list. Like this:

A = [[2,3,4], [5,-3,6]]
swap(A[0], A[1])
print(A)
#[[5,-3,6],[2,3,4]]

This does not work (Why?):

def swap(row1,row2):
 temp = row2
 row2 = row1
 row1 = temp

While this works (Why?):

def swap(row1,row2):
    for i in range(0,len(row2)):
     temp = row2[i]
     row2[i] = row1[i]
     row1[i] = temp
Jmei
  • 27
  • 3

1 Answers1

0

Python passes reference by value. In you first function, you pass in references to row1 and row2, you switch those references, but that doesn't change the list on the outside.

If you want to swap elements in a list like that, you should pass the list in so you modify the references in the list:

def swap(mylist):
    mylist[0], mylist[1] = mylist[1], mylist[0]

# This works for a list of ints
this_list = [1, 2]
swap(this_list)
this_list
# [2, 1]

# Or for a list of lists (Note that the lengths aren't the same)
that_list = [[1, 2, 3], [4, 5]]
swap(that_list)
that_list
# [[4, 5], [1, 2, 3]]

(Of note, also, is that you can do multiple assignments with python, so you don't need to use a temp variable.)

Stephen C
  • 1,966
  • 1
  • 16
  • 30
  • Thank you! how would it look if you take in two lists and not just one, and of unknown length? Guess you have to do a for loop? – Jmei Nov 27 '18 at 17:46
  • In the Python community, you might hear "arguments are passed by assignment", or even "call by sharing" or "call by object-sharing" ([the cryptic term for this evaluation strategy](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing)). – juanpa.arrivillaga Nov 27 '18 at 17:47
  • @Jmei If I understand correctly, it should work the same way. See my edit and see if you still have questions – Stephen C Nov 27 '18 at 17:54
  • Thanks! but the input is still one list? Just two lists inside one list. What if the function takes as input two separate lists, i.e. the function has two input arguments and not one. – Jmei Nov 27 '18 at 17:57
  • @Jmei If you want to switch the elements of two lists, then you would do it as you did in your last example. The only thing I would note is the multiple assignment thing, as I noted in my answer. (You don't need a `temp` to swap in python). – Stephen C Nov 27 '18 at 18:01
  • @Jmei The thing you need to be careful about here is if the lists have different lengths, you maybe have an `IndexError` on one hand. On the other, you may not end up swapping all the elements. Just something to be careful about depending on your desired functionality – Stephen C Nov 27 '18 at 18:02