5

I have this bubbleSort function in python that works perfectly.

def bubbleSort(arr):
n = len(arr)

# Traverse through all array elements
for i in range(n):

    # Last i elements are already in place
    for j in range(0, n-i-1):

        # traverse the array from 0 to n-i-1
        # Swap if the element found is greater
        # than the next element
        if arr[j] > arr[j+1] :
            arr[j], arr[j+1] = arr[j+1], arr[j]

I am new to python and I am having trouble understanding the code below the if statement. How does arr[j], arr[j+1] = arr[j], arr[j+1] work?

Whooper
  • 575
  • 4
  • 20

4 Answers4

2

If you have come from other programming languages, you might not be familiar with the concept of assigning multiple variables with a single statement.

That is what is happening here.

Ii I x, y = 3, 4 then x will have the value 3 and y will have the value 4

in this case

arr[j], arr[j+1] = arr[j+1], arr[j] could be rewritten as

arr[j] = arr[j+1]
arr[j+1] = arr[j]

However, that would not swap the variables (which happens in a single statement, as @Dimitar says). It would really need to be rewritten as

temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp

I hope that you can see why

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
2

In Python, tuples can be assigned directly. So the following code

arr[j], arr[j+1] = arr[j+1], arr[j]

if written as this, you would understand it better

(arr[j], arr[j+1]) = (arr[j+1], arr[j])

The code first creates a tuple containing (arr[j+1], arr[j]), then assign it correspondingly to arr[j], arr[j+1], which effectively swaps the two elements.

In other languages, you have to write

temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp

which is just unnecessary in Python, given that you can assign tuples directly.

iBug
  • 35,554
  • 7
  • 89
  • 134
1

Basically it is just swapping the values of arr[j] and arr[j+1]. arr[j] gets the value of arr[j+1] and arr[j+1] gets the value of arr[j].

Dimitar
  • 160
  • 1
  • 1
  • 10
-1

The last line could also be written as: (arr[j], arr[j+1]) = (arr[j+1], arr[j])

That means:

  1. Pack elements arr[j+1] and arr[j] into an array.
  2. Unpack them again.
  3. Assign them to arr[j] and arr[j+1].

The outer parentheses can be omitted in this case. What the lines does is basically swap elements j and j+1 of arr.

A similar statement without array destructuring would be:

tmp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = tmp
Felix
  • 129
  • 9