Python Forum

Full Version: swap elements in list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all

So the only way i can think of to swap two elements in list with the following

def swap(arr, pos1, pos2):
I wonder if there is away where I dont have to send the position of elements to be swapped. Instead by sending references to those elements in list. Like what we do in c or c++. I cant get my head around how the references work in this case in python.

Many thanks
>>> mylist = [1, 2, 3, 'hello', 'goodbye', 'Saturday']
>>> mylist
[1, 2, 3, 'hello', 'goodbye', 'Saturday']
>>> mylist[3], mylist[2] = mylist[2], mylist[3]
>>> mylist
[1, 2, 'hello', 3, 'goodbye', 'Saturday']
>>>
So, you question is about the following: If I have memory addresses of item[i] and item[j] (alist = [item[0], ... , item[N]], can I swap items without calling __getitem__, e.g. without accessing items via [ ... ]?. You are likely can do this using ctypes module, probably by means of ctypes.memmove function and/or sys.getsizeof function.
I think, the following code snippet could help you to write a swapper what you want.
Note, in this case you probably will need to take into account types of list elements, take care about references and internal structure of underlying PyObjects. So, this way is unstable and probably will lead to crash the Python interpreter.

Another approach could be much simpler, you can write a help function that returns index of the element by its address (get_index(address = id(item[i]))). When indices of elements are known, they can be easily swapped as @Larz60+ pointed out.
my_items = [1, 2, 3, 4, 5]


def swap(arr, item1, item2):
    index1 = my_items.index(item1)
    index2 = my_items.index(item2)
    arr[index1], arr[index2] = arr[index2], arr[index1]

    
swap(my_items, 2, 5)
print(my_items)
Output:
[1, 5, 3, 4, 2]