Python Forum

Full Version: Need help with weird tuple syntax
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I'm learning Python through an example below. However, I see a line that is weird. The line is marked as # mark-1. I understood that "," is used to create a tuple. And a tuple is a sequence of immutable Python objects. However, the line of code contains a part that puzzles me: nums[i] = nums[i] - this part seems to change the element of the tuple. What's going on?

class Example:
  def perm(self, nums):
        def backtrack(start, end):
            if start == end:
                ans.append(nums[:])
            for i in range(start, end):
              nums[start], nums[i] = nums[i], nums[start]  # mark-1
              backtrack(start+1, end)
              nums[start], nums[i] = nums[i], nums[start]  # mark-2
                
        ans = []
        backtrack(0, len(nums))
        return ans
  
  # Print the ans[]
  def print(self, ans):
    for x in ans:
      print(" ".join(map(str, x)))
This line is equivalent to
temp = (nums[i], nums[start])
nums[start], nums[i] = temp
nums[start], nums[i] = nums[i], nums[start]
That's convenient way to swap values in python
in slow motion this will be evaluated as follows
1. on the right hand-side create tuple with two values - nums[i] and nums[start]
2. unpack that tuple into nums[start] and nums[i]. that is called iterable unpacking. i.e. you can do something like a, b = [1, 2] in which case a=1 and b=2
Of cource nums should be mutable object (e.g. list, dict, etc.), i.e. it will not work if nums is a tuple

it's equivalent to
foo = num[i]
num[i] = num[start]
num[start] = foo
but without the need of third variable to hold one of the values temporarily