Search code examples
pythontuplescomma-operator

Is this comma-separated Python line creating a tuple?


I was looking at different discussions for this LeetCode problem, (basically, we need to remove all instances of a given value in an array, without creating or using another array) and I came across this particular solution:

def removeElement(self, nums, val):
  start, end = 0, len(nums) - 1
  while start <= end:
      if nums[start] == val:
          nums[start], nums[end], end = nums[end], nums[start], end - 1
      else:
          start +=1
  return start

I don't understand what is happening in this line:

nums[start], nums[end], end = nums[end], nums[start], end - 1

This comma syntax is unfamiliar to me. I have searched in the Python docs and here in Stack Overflow and learned that in Python, separating elements with commas produces a tuple, but for the life of me, I don't understand if that's what's happening here, since the "newly created tuple" is not being assigned to anything (there's even an assignment statement in there). Unless this has nothing to do with tuples and something else entirely is happening here.

I would like help understanding this line.


Solution

  • nums[start], nums[end], end = nums[end], nums[start], end - 1 The right side of the assignment creates indeed a tuple. The left side unpacks the tuples straightaway. Perhaps its easier to understand if you would split it up into two assignments:

    # create a tuple: (nums[end], nums[start], end - 1)
    atuple = nums[end], nums[start], end - 1
    
    # unpack the tuple into: nums[start], nums[end], end
    nums[start], nums[end], end = atuple
    
    # To make it more clear, here's an example using basic values
    another_tuple = 1, 2, 3
    
    # unpack the tuple -> a = 1, b = 2, c = 3
    a, b, c = another_tuple