Python Forum
Need help with weird tuple syntax - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Need help with weird tuple syntax (/thread-14706.html)



Need help with weird tuple syntax - mwskz8 - Dec-13-2018

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)))



RE: Need help with weird tuple syntax - Gribouillis - Dec-13-2018

This line is equivalent to
temp = (nums[i], nums[start])
nums[start], nums[i] = temp



RE: Need help with weird tuple syntax - buran - Dec-13-2018

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