Python Forum
Need help with weird tuple syntax
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with weird tuple syntax
#1
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)))
Reply
#2
This line is equivalent to
temp = (nums[i], nums[start])
nums[start], nums[i] = temp
Reply
#3
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tuple generator, and function/class syntax quazirfan 3 3,882 Aug-10-2021, 09:32 AM
Last Post: buran
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 2,822 Nov-04-2020, 11:26 AM
Last Post: Aggam
  [split] Python beginner: Weird Syntax Error mnsaathvika 1 2,137 Jul-22-2019, 06:14 AM
Last Post: buran
  Code syntax with underscore and assigning to a tuple santoshbwn 1 1,955 Jun-24-2019, 12:05 PM
Last Post: ThomasL
  How to get first line of a tuple and the third item in its tuple. Need Help, Anybody? SukhmeetSingh 5 3,197 May-21-2019, 11:39 AM
Last Post: avorane
  Python beginner: Weird Syntax Error mentoly 5 10,329 Oct-13-2017, 08:06 AM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020