0

I am trying to write a simple swap function, where the elements of an array get swapped once. The idea is I want to swap it once and check if it is the same as the unswapped array (which it will be for some cases, when all the elements are same, or something like that)

def swap(arr, pos):
    if pos <= len(arr) - 1 and num != 0:
        arr[pos], arr[pos + 1] = arr[pos + 1], arr[pos]
    else:
        pass
    return arr

some = [1,2,3,4]
#print(some)
for i in range(len(some) - 1):
    arr0 = some
    arr1 = swap(some, i)
    print(arr0, arr1)

And the output for this is:

[2, 1, 3, 4] [2, 1, 3, 4]
[2, 3, 1, 4] [2, 3, 1, 4]
[2, 3, 4, 1] [2, 3, 4, 1]

And I'm expecting something like:

[1, 2, 3, 4] [2, 1, 3, 4]
...

Why does the arr0 array get swapped?

3 Answers3

0
arr0 = some[:]

this should help you, it will copy the instance of the array not the location of it because when you make change to your some this will effect every array that is a directional copy of it

0

use copy() method.

arr0 = some.copy()

Code:

def swap(arr, pos):
    if pos <= len(arr) - 1  and num != 0:
        arr[pos], arr[pos + 1] = arr[pos + 1], arr[pos]
    else:
        pass
    return arr

some = [1,2,3,4]
#print(some)
for i in range(len(some) - 1):
    arr0 = some.copy()
    arr1 = swap(some, i)
    print(arr0, arr1)

Output:

[1, 2, 3, 4] [2, 1, 3, 4]
[2, 1, 3, 4] [2, 3, 1, 4]
[2, 3, 1, 4] [2, 3, 4, 1]
Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25
0

Other answers have made it clear. I just want to say, why not write

def swap(arr, pos):
    if pos <= len(arr) - 1  andpos < 0:
        arr[pos], arr[pos + 1] = arr[pos + 1], arr[pos]
    else:
        pass
    return arr

some = [1,2,3,4]
#print(some)
for i in range(len(some) - 1):
    print("before swap: ", some)
    swap(some, i)
    print("after swap: ", some)

Then you do not need to copy the list. Just print swap log in two lines.

Nathan Hardy
  • 156
  • 6