Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Passing a list by reference
#1
Hi all, I'm trying to do a sort function and I'm having some trouble. The function is actually not sorting, it is something with passing the arguments that I don't understand. I know that the lists are passed by reference therefore this example should work, but it doesn't.
p/s please don't tell my about build-in function .sort()

import sys
from random import randint


def switch (a,b):
    temp = a
    a = b
    b = temp

def sortList(data):
    for x in range (len(data)):
        for y in range (len(data)):
            if data[x] > data[y]:
                switch(data[x],data[y])

L = []
data = int(input("how many numbers do you want?: "))
for i in range(data):
    L.append(randint(1,1000000))
print('unsorted',L)
sortList(L)
print('sorted',L)
===================output==================================================

how many numbers do you want?: 10
unsorted [365283, 240490, 441964, 411424, 78927, 737039, 305545, 808196, 595894, 857359]
sorted [365283, 240490, 441964, 411424, 78927, 737039, 305545, 808196, 595894, 857359]
Reply
#2
Your function switch() must return the new values:

def switch(a, b):
    return b, a

a = 1
b = 2
a,b = switch(a,b)
Or, more directly...

def sortList(data):
    for x in range(len(data)):
        for y in range(len(data)):
            if data[x] > data[y]:
                data[x], data[y] = data[y], data[x]
Reply
#3
You're not passing lists to switch, you are passing the values in the list. So the actual exchange isn't involving the lists.

Is this homework? Because this is just a really bad idea all around. But assuming it's homework, have you covered tuple assignment?

data[x], data[y] = data[y], data[x]
That will handle what the swap function does. Otherwise you will need to either do the swap stuff in the sortList function, or pass three things to the swap function: The whole list and the two indexes.

Note that your loop is going to mess it all up. You are looping through all of the indexes. So say you start the loop for x == 5. The first y value will be 0, and you will be comparing data[5] to data[0], which is way before data[5]. You need to look into sorting algorithms. This kind of looks like bubble sort, but there you just check adjacent indexes, and you check them until no further swaps are needed.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
(Jun-30-2018, 03:23 AM)ichabod801 Wrote: 1
data[x], data[y] = data[y], data[x]
interesting :)

No this is not a homework assignment. Yes it is a bubble sort.
I'm learning python by myself and perhaps I tried to bring some C++ in it:) Anyway, I see where the problem is: switch(I should've call it swap) function doesn't pass by reference as I understand.

Thanks @ichabod801 and @gontajones.
Reply
#5
(Jun-30-2018, 03:54 AM)virgik89 Wrote: Anyway, I see where the problem is: switch(I should've call it swap) function doesn't pass by reference as I understand.

No, they are passed as references - only as constant references. A function cannot change a reference to its argument - but it can change the referenced object content.

Thus, immutable objects cannot be changed within a function - but elements of a mutable object may be.

This simple function will change the list in the outer scope even if you don't return the list reference - but this will cause a side effect, and we don't want that, do we ?!
def foo(list_, value):
    list_.append(value)
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#6
Traditional language call by value and call by reference take a backseat in Python to call by object reference.

In addition to @volcano63's excellent comments, see the following which discusses all three concepts in Python: https://stackoverflow.com/questions/1329...-reference

Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply
#7
Thanks everyone.
Here is a good example that talks about immutability which make sense now to me how those references work.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to define a variable in Python that points to or is a reference to a list member JeffDelmas 4 2,596 Feb-28-2021, 10:38 PM
Last Post: JeffDelmas
  Passing List of Objects in Command Line Python usman 7 3,087 Sep-27-2020, 03:45 PM
Last Post: ndc85430
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,513 Sep-07-2020, 08:02 AM
Last Post: perfringo
  Mathplotlib - passing reference to axs to function qmfoam 5 2,903 Aug-17-2020, 09:02 PM
Last Post: qmfoam
  reference in pop function for linked list oloap 0 1,540 Mar-14-2020, 05:52 PM
Last Post: oloap
  set a new object node in a linked list via reference oloap 2 2,056 Mar-13-2020, 09:45 PM
Last Post: oloap
  Problem with List Reference CH_NoLuck 1 1,657 Feb-22-2020, 03:27 AM
Last Post: CH_NoLuck
  Passing an argument by reference Exsul 12 4,603 Aug-22-2019, 07:29 AM
Last Post: DeaD_EyE
  Passing by reference or value CanadaGuy 4 2,915 Nov-12-2018, 08:44 PM
Last Post: CanadaGuy
  List 3 dimensions reference does not work Mario793 1 2,623 Mar-02-2018, 12:35 AM
Last Post: ka06059

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020